How do I encode a file name for download?

Viewed 26697

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?

9 Answers

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.

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 + """")
Related