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

asp.net, encoding, response

Solution

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 + "\"");

Problem

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.

Original source