ASP.net download file Using HttpContext.Current.Response fileName - c#

I am trying to download a file using System.Web.HttpContext.Current.Response using the following code:
HttpResponse objResponse = System.Web.HttpContext.Current.Response;
I am encoding the file name using:
FileName = Uri.EscapeDataString(FileName);
The file is downloading correctly, except when I have comma or dot in the file name.
In that case, while downloading the file, the explorer cannot decode the comma back.
For instance:
Original file name: Testing, File
Encoded name: Testing%2C%20file
Downloaded file name: Testing%2C file
Is there any way to code/encode the file name, in order to keep the commas and dots?

for example, you can use:
public ActionResult DownloadFileXML(string filePath)
{
string fileName = Path.GetFileName(filePath);
return File(filePath, "application/xml", fileName);
}

Related

Open pdf from byte array ios xamarin c#

I have a byte array that contains a pdf document and I want to open it in an ios application.
This is my code so far:
public static string WriteFileFromByteArray(string fileName, byte[] bytes)
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine(documentsPath, fileName);
File.WriteAllBytes(fileName, bytes);
return filePath;
}
Does any one know how to do so?
Not sure where exactly you are stuck up.
But there is an issue in the below line of code you have posted.
File.WriteAllBytes(**fileName**, bytes);// on this code you are using filename instead of filepath.
Use filePath variable instead of fileName as it just contains the name of a file.
Refer the below link for PDF viewer.
http://forums.xamarin.com/discussion/631/open-a-pdf-with-the-built-in-pdf-viewer

Add a hyperlink to grid column

I'd like to have a link on the FileName column, so users can click and open a PDF file (no download, only open to view). This is what I have tried, but I don't know how to pass the file name to the server function.
columns.Bound(p => p.FileName)
.ClientTemplate( "/#= FileName #")
The FileHelper.GetFullPath method is a server function to generate the full path for the file. The full path should be:
http://servername/applicationname/filefolders/filename.pdf
You can't implement the PDF download on the client-side easily. You should instead stream the PDF file using another action method.
Try this instead:
.ClientTemplate("<a href='" + Url.Action("GetPdf", "Home") + "?fileName=#= FileName #'>#=FileName#</a>");
public ActionResult GetPdf(string fileName)
{
string path = FileHelper.GetFullPath(fileName);
FileStream stream = new FileStream(path, FileMode.Open);
return File(stream, "application/pdf", fileName + ".pdf");
}

Use content of FileUpload

I am attempting to add a file import function to an admin webpage where a CSV file will be imported from a local C: drive
I've just realized that string filePath = Path.GetFileName(FileUpload1.FileName); doesn't actually allow the client path to be read and only gives the filename.
protected void btnImportData_Click(object sender, EventArgs e)
{
List<CSVFile> entries = new List<CSVFile>();
string filePath = Path.GetFileName(FileUpload1.FileName);
using (TextFieldParser parser = new TextFieldParser(filePath))
{
//Other code
}
}
Currently the line TextFieldParser parser = new TextFieldParser(filePath) gives an error as I can't get the full path to the CSV.
Is it possible to load the contents of FileUpload1 into variable parser instead? I can see the control has content but not sure how or if it's possible?
The FileName property is simply the filename the browser sent, and is not yet physically stored on the server. To do so, you'll need to save it first:
string filePath = String.Format({0}{1}", System.IO.Path.GetTempPath(), FileUpload1.FileName); // Save to temp directory
FileUpload1.SaveAs(filePath);
using (TextFieldParser parser = new TextFieldParser(filePath))
{
//...
}
File.Delete(filePath); // Delete the file if you're done with it
Also, if TextFieldParser can take in a System.IO.Stream, you won't even need to save the file to disk first:
using (TextFieldParser parser = new TextFieldParser(FileUpload1.FileContent)) // Read stream
{
//...
}
Take into account that the file is not stored yet on the server so there is no path. FileName is just that: a file name and not a full path.
If you require the file to exist on the file system in order to parse it, you'll need to first save it.

Returning An Xml String To Client Code From C#

I am reading a file from the user files that contains xml that I am processing in a Generic Handler and then passing to the client.
The problem I am having is when I pass the string of xml to the client. Its not in the proper format. It removes the root tag and "<xml 1.0>" tag entirely when looking at it through the client code.
I am looking for some code to preserve the xml string as is when it gets to the client.
I am reading the xml out of a file using System.IO on the server..
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
file.SaveAs(fileName);
string msg = File.ReadAllText(fileName);
File.Delete(fileName);
context.Response.Write(msg);
}
}
The xml always starts at "Gambardella..." For some reason it cannot read the beginning of the file when being send to the cient.
Here is an image of the sample xml..
The data is sent out of the handler fine but the client cuts off the top information. It looks like the plugin I am using is storing the (or getting) the data from an iframe. Could the iframe maybe be the culprit in cutting off the beginning xml??
The sample client code I am using is here
You can simply use Response.WriteFile, instead of reading the file then sending it.
Response.WriteFile(fileName);
This will return the contents of the file with the correct HTTP Content-Type header. If the file has the XML declaration, it will not remove it.
Something like the following, based on your code and untested (an without a MemoryStream, as it is not needed in this case):
var file = context.Request.Files[0];
file.InputStream.CopyTo(context.Response.OutputStream)

Can not open a text file just after creating it from webservice

I am unable to open the file just after creating the file in c# webservice code .
The directory is not present initially. So the program creates the directory and the file. Then tries to open the file to write a line. But it fails to open the file. The error is the file is open in another process.
I tried to open the file from windows explorer. the file opens but error message is still coming.
I tried to delete the folder C:\Test, it says file is open is in WebDev.WebDevServer40.exe
Any help please.
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
if(!File.Exists(completeFileName))
{
Directory.CreateDirectory(path);
File.Create(completeFileName);
}
StreamWriter writer = File.AppendText(completeFileName);
writer.WriteLine(name);
writer.Flush();
writer.Close();
return "success";
}
File.Create returns a stream, but you're discarding it.
So (I think!) you either need to use the returned stream, or explicitly close it before trying to open a new stream to the same file.
You need to close the file, try:
File.Create(completeFileName).Close();
Use the File.AppendAllText instead.
This will create the file if it doesn't exist.
Your code would be as simple as
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
File.AppendAllText(completeFileName, name);
return "success";
}

Categories