Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the filename header is incomplete if this has space in ASP.NET MVC 3?

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.

enter image description here

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) ?

like image 323
Snake Eyes Avatar asked Sep 20 '12 06:09

Snake Eyes


2 Answers

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.

like image 20
cktech Avatar answered Oct 03 '22 16:10

cktech


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 ) + "\"");
like image 194
Damien_The_Unbeliever Avatar answered Oct 03 '22 17:10

Damien_The_Unbeliever