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.

- 35,627
- 39
- 202
- 311
-
1HttpUtility.UrlEncode is supported in WP7. – William Melani Jul 13 '12 at 15:30
-
Not supported when I select Metro and WP7.1 in PCL. – Muhammad Rehan Saeed Jul 13 '12 at 16:16
-
1They live in different locations and binaries, hence, why they are not available. – David Kean Aug 14 '12 at 07:14
2 Answers
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.

- 25,747
- 28
- 93
- 153

- 2,891
- 2
- 17
- 15
-
1Do you use both or either one of them? The docs for the two is identical except from the name of the method. – Cheesebaron Jul 03 '13 at 09:29
-
1
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.)

- 26,385
- 18
- 89
- 135