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

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


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...


I figured the best option would be to UrlEncode the filename

That's not the right way to put out-of-band characters in a header parameter such as Content-Disposition-filename, and only works (sometimes) in IE due to a bug. Actually it's a bit of a perennial problem: there is no right way.

If you need to put special characters in the downloaded filename, you can't do it reliably with Content-Disposition-filename. Instead, omit the ‘filename’ parameter from the Content-Disposition-attachment header, and leave the filename you want in the trailing part of the URL. In the absence of a filename parameter the browser will take it from the URL path, where URL-encoding is the right way to tackle special characters.


Quoting from this link

I've come across this myself. If you are able to change the spaces to %20s then IE7 will convert them correctly. Firefox though will take them literally ( at least when using the Content-disposition header) so you will need to do this for requests from IE7 only.

We did the following in our app. ( a tomcat based document repository)

String userAgent = request.getHeader("User-Agent");if (userAgent.contains("MSIE 7.0")) {    filename = filename.replace(" ", "%20");    }         response.addHeader("Content-disposition",    "attachment;filename=\"" + filename + "\"");