File reading and writing inside asp.net web application - asp.net

I have developed an ASP.NET web application in Visual Studio 2008.
I have an HTML document and one text file in the application, but both are not inside my application.
Both are outside, so when I try to run the same application in another system, I get an error because I am missing those files.
I want to include the files inside the application when I deploy it.
Below is the code I use to read and write the files:
//file write test.txt
FileStream file1 = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw1 = new StreamWriter(file1);
// Write a string to the file
sw1.Write(emailId);
// Close StreamWriter
sw1.Close();
// Close file
file1.Close();
// *** Write to file ***
// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.html", FileMode.Create, FileAccess.Write);
// Create a new stream to write to the file
StreamWriter sw = new StreamWriter(file);
// Write a string to the file
sw.Write(BodyLiteral.Text);
// Close StreamWriter
sw.Close();
// Close file
file.Close();
// *** Read from file ***
// Specify file, instructions, and privelegdes
file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);
// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);
// Read contents of file into a string
string cval = sr.ReadToEnd();
Response.Write(cval);
// Close StreamReader
sr.Close();
// Close file
file.Close();
//html file reading
string text = File.ReadAllText(#"D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\test.html");
Both of my files are in: D:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\
How can I deploy these two files with application so that the program will work on another system?

Your best bet would be Server.MapPath().
Example:
Put the files inside folder "file" (you can make a folder in your solution, by right clicking your solution and choose add folder)..
then right click the folder..choose existing item , and then choose your files..
To make the path to your files local.. use the follow
Server.MapPath("~\\files\\test.html");
Your code modified
FileStream file = new FileStream( Server.MapPath("~\\files\\test.html"), FileMode.Create, FileAccess.Write);

Best thing to do is to add the files to your solution.
In solution exploere you can right-click and add an existing item. Change your code to read from that location, so when you deploy your code it will be in a known location and part of the deployment.

Related

C# iText7 The process cannot access the file 'Tmp.pdf' because it is being used by another process

I'm using iText to create a PDF from a PDF template which is then emailed. The code is to be executed repeatedly. The created temporary file can't be deleted or overwritten. The error message is "The process cannot access the file 'Tmp.pdf' because it is being used by another process."
string path = Server.MapPath("files");
string tmp = path + #"\Tmp.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(path + #"\Template.pdf"), new PdfWriter(tmp));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
form.GetField("Content").SetValue(tmpItems.Text);
form.FlattenFields();
pdfDoc.Close();
// Email PDF
MailMessage mailMsg = new MailMessage();
Attachment data = new Attachment(tmp, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(tmp);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(tmp);
disposition.ReadDate = System.IO.File.GetLastAccessTime(tmp);
mailMsg.Attachments.Add(data);
File.Delete(tmp);
I assumed the file had been closed (pdfDoc.Close();) releasing the resource. The second time the code snippet is used (to create another version to be emailed) to overwrite the file, the error occurs at line 3. As a potential fix, I tried to delete the file but again the error occurs at the deletion point.
This is a very short snippet of code. What is the other process holding on to the file? What am I doing wrong?

What is the path of the Json file in Android at Xamarin.Forms?

I am developing an application for Android using Xamarin.
I have created a JsonData folder in the Android project and created a Setting.json file.
\MyApp\MyApp.Android\JsonData\Setting.json
In the properties, we set the Copy when new.
The following folders in the local environment contain the files.
\MyApp\MyApp.Android\bin\Debug\JsonData\Setting.json
I want to load this file in the actual Android device.
When I do this, it tells me that the file is missing.
Could not find a part of the path "/JsonData/Setting.json."
Try
{
var text = File.ReadAllText("JsonData/Setting.json", Encoding.UTF8);
var setting = JsonConvert.DeserializeObject<Setting>(text);
}
catch(Exception exception)
{
var error = exception.Message;
}
What is the path of the file in Android?
I think you're using File Handling in Xamarin.Forms incorrectly.
From the parameter of function File.ReadAllText, the app will access the file system to getSetting.json from folder JsonData in your android device.
The path of the file on each platform can be determined from a .NET Standard library by using a value of the Environment.SpecialFolder enumeration as the first argument to the Environment.GetFolderPath method. This can then be combined with a filename with the Path.Combine method:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
And you can read the file by code:
string text = File.ReadAllText(fileName);
In addition, from your code,I guess you want to Load your Embedded file( Setting.json) as Resources,right?
In this case,we should make sure the Build Action of your Setting.json is Embedded Resource.
And GetManifestResourceStream is used to access the embedded file using its Resource ID.
You can refer to the following code:
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("YourAppName.JsonData.Setting.json");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}
For more , you can check document : File Handling in Xamarin.Forms.
And you can also check the sample code here: https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithfiles/ .

XML does not get saved in asp.net

I have a problem saving my xml-file.
i use this XMLwriter :
using (XmlWriter writer = XmlWriter.Create("CarsXML.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("CarsXml");
foreach (Car item in cars)
{
writer.WriteStartElement("Car");
writer.WriteElementString("Brand", item.Brand);
writer.WriteElementString("Type", item.Type);
writer.WriteElementString("Price", item.Price);
writer.WriteElementString("Effect", item.Effect);
writer.WriteElementString("Year", item.year);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
Seems ok right? No compile errors..
I´ve also tried this just for testing :
XDocument doc = new XDocument(
new XElement("Root",
new XElement("Child", "content")
)
);
doc.Save("Root.xml");
Still no luck.. `ve trid this in a console app, and it works so the code must be fine..
I´ve also tried with a piece of code i found somewhere - using XmlDocument instead - but its the same deal.
What am i doing wrong?
When you are in a web application, the current directory is not the root directory of the web application. It's the directory where the IIS executable is, so that's somewhere in the Windows system directories.
Naturally you don't have write access to that directory from the web application, so you get some exception when you try to create a file there.
Specify the full path of the file that you want to create. You can use the MapPath method to get the physical path to a file from a virtual path. Example:
string fileName = Server.MapPath("/xmldata/CarsXML.xml");
using (XmlWriter writer = XmlWriter.Create(fileName))
...

Set images on Pdf using itextsharp

I am working on WCF service to create a pad file and want to set image on created pdf.
Below is my code. it gives me error "object reference not set to an object instance"
string str = System.Web.HttpContext.Current.Request.MapPath("App_Data/suc.png");
Image imgCheckBoxChecked = Image.GetInstance(str);
The other thing I try and it gives me error :Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\suc.png: Below is my other code
Image imgCheckBoxChecked = Image.GetInstance("App_Data/suc.png");
cell.AddElement(imgCheckBoxChecked);
cell.Colspan = 4;
table.AddCell(cell);
Any idea on how to solve this error and set image on pdf.
Thanks
You can use AppDomain.BaseDirectory to get directory to the main dll, after this you can use it to get the path to your image dll, like Path.Combine(AppDomain.BaseDirectory, "App_Data\\suc.png"), if you host service in ASP.NET, and the dll is in Bin directory you can use relative path like Path.Combine(AppDomain.BaseDirectory, "..\\App_Data\\suc.png")
string pdfPath = "~/PDF/File_1.pdf";
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/image.JPG"));
img.ScalePercent(100f);
Document doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath(pdfPath), FileMode.Create));
doc.Open();
doc.Add(new Paragraph(sb.ToString()));
doc.Add(img);
doc.Close();

FileUpload problem with Struts on server

I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.

Resources