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 StringExtensions
{
// 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);
}
}

The SpaceToNbsp method simply replaces spaces with the string " ". The UrlEncode and UrlDecode methods use the HttpUtility class's UrlEncode and UrlDecode methods.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.