Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20")) return + instead of %20?

I'm having a problem with a file download where the download is replacing all the spaces with underscores.

Basically I'm getting a problem here:

Response.AddHeader("Content-Disposition", 
    "attachment; filename=" + someFileName);

The problem is that if someFileName had a space in it such as "check this out.txt" then the user would be prompted to download "check_this_out.txt".

I figured the best option would be to UrlEncode the filename so I tried

HttpUtility.UrlEncode(someFileName);

But it's replacing the spaces with plus signs, which stumped me. So then I just tried

HttpUtility.UrlEncode(HttpUtility.UrlDecode("%20"))

and the decode works properly and gives me a space, but the encode takes the space and then gives me the plus sign again.

What am I missing here, is this correct? If so, how should I properly encode spaces into %20's, which is what I need.

like image 812
Joseph Avatar asked Oct 13 '09 16:10

Joseph


People also ask

How do I use HttpUtility UrlEncode?

The HttpUtility. UrlEncode method uses UTF-8 encoding by default. Therefore, using the UrlEncode method provides the same results as using the UrlEncode method and specifying UTF8 as the second parameter. UrlEncode is a convenient way to access the UrlEncode method at run time from an ASP.NET application.

What is HttpUtility Urldecode?

HttpServerUtility.UrlDecode Method (System.Web)Decodes a string that was encoded for HTTP transmission and then sent to the server in a URL. To encode or decode values outside of a web application, use the WebUtility class.

How do you know if a string is already URL encoded or not?

So you can test if the string contains a colon, if not, urldecode it, and if that string contains a colon, the original string was url encoded, if not, check if the strings are different and if so, urldecode again and if not, it is not a valid URI.

What is Server UrlEncode?

The URLEncode method applies URL encoding rules, including escape characters, to a specified string. URLEncode converts characters as follows: Spaces ( ) are converted to plus signs (+). Non-alphanumeric characters are escaped to their hexadecimal representation.


1 Answers

Basically both %20 and + are valid ways of encoding a space. Obviously the UrlEncode method has to pick one of the options... if it chose to do the other way, someone else would have asked why UrlEncode(UrlDecode("+")) returned "%20"...

You could always encode it, then just do a straight string replace on "+" for "%20". I think that would work...

like image 51
Jon Skeet Avatar answered Oct 07 '22 00:10

Jon Skeet