Search code examples
windows-phone-7microsoft-metrourlencodeportable-class-library

Portable Class Library HttpUtility.UrlEncode


I understand that making web requests is quite well supported in the Portable Class Library. Is there any equivelant of HttpUtility.UrlEncode in the PCL? I need it for Windows Phone and Metro applications.


Solution

  • WebUtility

    In portable class libraries lucky enough to be targeting .NET 4.5 (e.g. Profile7), many of the HttpUtility methods have siblings in System.Net.WebUtility.

    using System.Net;
    
    WebUtility.UrlEncode("some?string#");
    

    Potential Warning

    While some of the sibling methods appear to be identical to their HttpUtility counterparts, this one has a slight difference between the resulting encodings. WebUtility.UrlEncode generates uppercase encodings while HttpUtility.UrlEncode generates lowercase encodings.

    WebUtility.UrlEncode("?") // -> "%3F"
    HttpUtility.UrlEncode("?") // -> "%3f"
    

    Make It Backwards Compatible

    If you are dependent on your PCL code generating exactly what you would have generated with prior HttpUtility code, you could create your own helper method around this method and regex it.

    using System.Text.RegularExpressions;
    
    public static string UrlEncodeOldSchool(string value) {
        var encodedValue = WebUtility.UrlEncode(value);
        return Regex.Replace(encodedValue, "(%[0-9A-F]{2})",
                             encodedChar => encodedChar.Value.ToLowerInvariant());
    }
    

    (Even though this is a simple one, always regex at your own risk.)