34

The regular .Net framework contains HttpUtility.UrlEncode in the System.Web Assembly and in Silverlight it appears it was moved to System.Windows.Browser. But in Windows Phone 7 (which I thought was the same as Silverlight) I can't seem to find a proper way to UrlEncode anything. Neither of the previously mentioned assemblies are available in the Windows Phone 7 environment.

Luke Foust
  • 2,234
  • 5
  • 29
  • 36

3 Answers3

59

Silverlight has the Uri.EscapeUriString and Uri.EscapeDataString which can be used to URL-encode portions of a URI such as query strings and path components and such.

Even in the desktop framework, you should never take a dependency on System.Web.dll just for HttpUtility, although many developers still do it. This is bad for 3 reasons.

  • The assembly is very large and loading it can add significant delays to your application.
  • You will be bloating the working set of your process for about 20 lines of code.
  • It makes your application require the full framework since System.Web is not in the client profile.

In addition to the Uri escaping methods described above, if you need HtmlEncode, I would just rip code off that someone else wrote and drop it in your application.

Josh
  • 68,005
  • 14
  • 144
  • 156
  • 5
    +1, also the correct approach in any .NET client application not just Silverlgiht. HttpUtility is in the System.Web.dll which is designed to deliver the Server end of the Web. – AnthonyWJones Apr 04 '10 at 12:26
  • Indeed I just wrote a twitter view / search app which uses this so they do work. – RoguePlanetoid Apr 07 '10 at 12:05
  • Regarding HtmlEncode/HtmlDecode, it's not only at System.Web of full .NET framework: .NET 4 Client Profile has System.Net.WebUtility, Silverlight has System.Windows.Browser.HttpUtility and Windows Phone has System.Net.HttpUtility – George Birbilis Mar 20 '14 at 22:31
  • at http://weblog.west-wind.com/posts/2009/Feb/05/Html-and-Uri-String-Encoding-without-SystemWeb it is suggesting: "pre-process for + sign space formatting since System.Uri doesn't handle it, plus literals are encoded as %2b normally so this should be safe" - public static string UrlDecode(string text) {text = text.Replace("+", " "); return System.Uri.UnescapeDataString(text); } – George Birbilis Mar 20 '14 at 22:36
25

HttpUtility.UrlEncode and HttpUtility.UrlDecode are in Windows Phone 7, they just got moved.

Look for them in System.Net.HttpUtility in assembly System.Windows.dll.

Heinrich Ulbricht
  • 10,064
  • 4
  • 54
  • 85
John Melville
  • 3,613
  • 28
  • 30
0

Now it is solved. You can use :

Windows.Data.Html.HtmlUtilities.ConvertToText("your_html_string");
Mushfiq
  • 759
  • 1
  • 8
  • 41