In C# ASP.Net Website, to transfer the file to client I am using
String file_path = Server.MapPath("~/files/"+file_name);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + file_Name);
HttpContext.Current.Response.TransmitFile(file_path);
HttpContext.Current.Response.End();
It is working perfectly, but when the file name contains any spaces the downloaded file has a name only up to the first word. For ex: If my file name is "This is demo.txt"
then the downloaded file name becomes "This"
with no extension. Hence the user downloading it is not able to identify its type.
How can we avoid happening it for file name containing spaces?
I tried using
String file_path = "'"+Server.MapPath("~/files/"+file_name)+"'";
But it didn't work.
Also its not possible for me to replace ( with '_' or '-') or remove all the spaces present in the file name which are present on the server.
You should enclose the filename in quotes.
And if you are using VS2015 or later, you can make it a bit tidier with string interpolation:
Also, the filename in the header does not have to be the same as the name of the file. The filename in the header is only a suggestion to the user.
For full details, see RFC 6266 "Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)," especially with regard to which characters may cause problems in a filename.