Convert url from utf-8 to iso-8859-1 encoding

I have a file: // links with non-English characters that are UrlEncoded in UTF-8. In order for these links to work in the browser, I have to transcode them.

file://development/H%C3%A5ndplukket.doc 

becomes

 file://development/H%e5ndplukket.doc 

I have the following code that works:

 public string ReEncodeUrl(string url) { Encoding enc = Encoding.GetEncoding("iso-8859-1"); string[] parts = url.Split('/'); for (int i = 1; i < parts.Length; i++) { parts[i] = HttpUtility.UrlDecode(parts[i]); // Decode to string parts[i] = HttpUtility.UrlEncode(parts[i], enc); // Re-encode to latin1 parts[i] = parts[i].Replace('+', ' '); // Change + to [space] } return string.Join("/", parts); } 

Is there a cleaner way to do this?

+4
source share
3 answers

I think pretty clean actually. It reads, and you said that it works correctly. As long as the implementation is hidden from the consumer, I would not worry about squeezing the latest improvement.

If you do this operation excessively (for example, hundreds of executions for each event), I would think of doing an implementation from UrlEncode / UrlDecode and passing them to each other in order to get better performance there, removing the need for line splitting / joining, but testing would have to prove it anyway and definitely would not be "clean" :-)

+1
source

Until I see a real way to change it, in order to change the situation, do not replace + with a space in front of your UrlEncode so that it turns into% 20?

0
source

admittedly ugly and not entirely improved, but can transcode all of this (avoid split / iterate / join). Replace ("% 2f", "/")

I don’t understand the code that wants to save space in the final result - it looks like you haven’t finished something that is really encoded if it still has spaces in it?

0
source

All Articles