How to encode a URL in WinForms?

Andrew picture Andrew · May 21, 2011 · Viewed 21.2k times · Source

I'm creating a Windows application and I need to pass an encoded URL. But I'm not sure how to encode it in WinForms C#?

Answer

Chris Fulstow picture Chris Fulstow · May 21, 2011

If you need to URL-encode data for a querystring, you can use either Uri.EscapeDataString or, if you don't mind referencing System.Web, HttpUtility.UrlEncode:

var rawString = @"this & that";
var uriEncoded = Uri.EscapeDataString(rawString);
var httpUtilityEncoded = HttpUtility.UrlEncode(rawString);

They're very similar but can produce subtly different results in the way special characters, like spaces, are encoded:

Console.WriteLine(uriEncoded);
// uriEncoded = "this%20%26%20that"

Console.WriteLine(httpUtilityEncoded);
// httpUtilityEncoded = "this+%26+that"