Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...