28

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.

Muhammad Rehan Saeed
  • 35,627
  • 39
  • 202
  • 311

2 Answers2

36

Use Uri.EscapeUriString and Uri.EscapeDataString

The only difference between the two is that EscapeDataString also encodes the RFC 2396 reserved characters which includes these characters ;/?:@&=+$,

It is important to note that neither of these methods encodes the RFC 2396 unreserved characters which includes -_.!~*'() So if you need these encoded then you will have to manually encode them.

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
Jon
  • 2,891
  • 2
  • 17
  • 15
15

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

patridge
  • 26,385
  • 18
  • 89
  • 135