How do I encode a file name for download?
Solution 1
I encode file name like this for downloading,
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename= " + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Solution 2
Based on ZZ Coder answer, and because I'm using FileResult, I decided to encode the file name as:
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)
Solution 3
We had an issue where Chrome was changing filenames that contained underscores to the name of the page the file was being downloaded from.
Using HttpUtility.UrlPathEncode(filename)
as suggested by Furkan Ekinci in the comments fixed it for us.
Solution 4
The only trick that works (in all browsers) for me is:
Dim headerFileName As String = IIf(Request.Browser.Browser = "InternetExplorer" Or Request.UserAgent.Contains("Edge"), Uri.EscapeDataString(file.Name), file.Name)
Response.AddHeader("Content-Disposition", "attachment; filename=""" + headerFileName + """")
Solution 5
This issue has been known for years. As far as I can tell, there currently is no interoperable way to do this, so the answer is to only support one set of browsers, or to do User Agent sniffing.
Test cases and links at: http://greenbytes.de/tech/tc2231/
Related videos on Youtube
eKek0
I'm a software developer living in Santiago del Estero, one of the smallest towns in Argentina. I'm also a system analyst, and program in Delphi and ASP.NET with C#. Currently, I'm working in a bank developing in-house software.
Updated on December 21, 2020Comments
-
eKek0 over 3 years
When the file name is "Algunas MARCAS que nos acompañan" ASP.NET MVC raise an
System.FormatException
when I try to download that file. But if the file name is "Asistente de Gerencia Comercial" it doesn't.I guess this is because something related to
UTF-8
encoding, but I don't know how to encode that string.If I'm right, how can I encode the string in
UTF-8
encoding? If I'm not right, what is my problem?-
Sixten Otto over 14 yearsHow are you sending the file back to the user now? Using
System.Web.Mvc.FileResult
? Can you post your code? -
Sixten Otto over 14 yearsThe weird thing is that
System.Web.Mvc.FileResult
internally usesSystem.Net.Mime.ContentDisposition
to generate the header that it adds to the response. I would have expected that class to be able to handle whatever string encoding is necessary to make this work.
-
-
Cosmin over 9 yearsThis replaces spaces with +, which may not be what you want.
-
Oskar Berggren about 8 yearsNOTE: For the correct solution in modern times, see RFC6266: tools.ietf.org/html/rfc6266
-
Furkan Ekinci over 4 yearsHttpUtility.UrlEncode causes replacing spaces with plus signs, HttpUtility.UrlPathEncode is solution for plus sign problem.