I met today an issue, it is strange for me but, maybe, not for experts in C# field.
I have a function called Download
like this ( a piece of code !)
public void Download (string path){
HttpContext.Current.Response.ContentType = "application/octet-stream";
try {
....//process a 'filePath' variable using the 'path' parameter
using ( FileStream sourceFile = new FileStream( filePath, FileMode.Open ) ) {
...
HttpContext.Current.Response.AddHeader( "Content-Disposition", "attachment; filename=" + Path.GetFileName( filePath ) );
HttpContext.Current.Response.AddHeader( "Content-Length", fileSize.ToString() );
HttpContext.Current.Response.BinaryWrite( getContent );
}
...
}
If file name mentioned and stored in path
/filePath
variable contains space like
PR SimpleTest.xls
then the download box contains file name like PR
with nothing additional.
If that file name has NO space (like PR_SimpleTest.xls
) then the header comes with PR_SimpleTest.xls
and I can download as such (appears full filename with his extension).
There are solution(s) to solve issue in case when file name contains space(s) ?
The answer above using:
Server.UrlEncode(strFileName)
did not work for me, it resulted in a filename that was:
"My+Long+Filename.txt"
whereas the first solution using surrounding the filename with quotes produces:
"My Long Filename. txt"
which is what we want.
A google search for http headers spaces finds this Knowledge Base article which suggests surrounding the filename with quotes. E.g.
HttpContext.Current.Response.AddHeader(
"Content-Disposition",
"attachment; filename=\"" + Path.GetFileName( filePath ) + "\"");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With