How do I decode a URL parameter using C#?

Tom picture Tom · Sep 10, 2009 · Viewed 177.8k times · Source

How can I decode an encoded URL parameter using C#?

For example, take this URL:

my.aspx?val=%2Fxyz2F

Answer

ogi picture ogi · Oct 2, 2010
string decodedUrl = Uri.UnescapeDataString(url)

or

string decodedUrl = HttpUtility.UrlDecode(url)

Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:

private static string DecodeUrlString(string url) {
    string newUrl;
    while ((newUrl = Uri.UnescapeDataString(url)) != url)
        url = newUrl;
    return newUrl;
}