Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File download problem: filename with spaces truncated!

Tags:

asp.net

c#-4.0

While I am working on code to download file from server using :

Response.AddHeader("Content-Disposition", "attachment; filename=" + 
Server.UrlPathEncode(Path.GetFileName(_Filename)));

The problem is while having spaces in the file name, with this code the server split automatically while finding the first space!

I'm hoping to know Why & what is the solution for that?

like image 402
Abdelrahman ELGAMAL Avatar asked Sep 17 '10 15:09

Abdelrahman ELGAMAL


People also ask

How do you handle spaces in file names?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified.

Do spaces in file names cause problems?

Avoid spacesA space in a filename can cause errors when loading a file or when transferring files between computers. Common replacements for spaces in a filenames are dashes (-) or underscores (_). Alternatively you can also use a technique called camelCase which uses letter case to separate name elements.

Can a filename include spaces?

Don't start or end your filename with a space, period, hyphen, or underline. Keep your filenames to a reasonable length and be sure they are under 31 characters. Most operating systems are case sensitive; always use lowercase. Avoid using spaces and underscores; use a hyphen instead.


1 Answers

You need to wrap the filename in double quotes.

string filename = Server.UrlPathEncode(Path.GetFileName(_Filename)));
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

Otherwise the code assumes that the filename ends at the first space.

You might not need the Server.UrlPathEncode.

like image 192
ChrisF Avatar answered Oct 25 '22 19:10

ChrisF