Make string extensions to URL encode and decode strings in C#

URL encoding converts special characters into numeric sequences so you can include them safely in a URL. The following code creates extension methods for the string class that lets you convert spaces into the string " " and that URL encode and decode strings.
static class StringExtensionsThe SpaceToNbsp method simply replaces spaces with the string " ". The UrlEncode and UrlDecode methods use the HttpUtility class's UrlEncode and UrlDecode methods.
{
// Extension to replace spaces with
public static string SpaceToNbsp(this string s)
{
return s.Replace(" ", " ");
}
// Url encode an ASCII string.
public static string UrlEncode(this string s)
{
return HttpUtility.UrlEncode(s);
}
// Url decode an ASCII string.
public static string UrlDecode(this string s)
{
return HttpUtility.UrlDecode(s);
}
}


Comments