Title: Make string extensions to URL encode and decode strings in C#
When you URL encode a string, you convert special characters into numeric sequences thath are safe to use in a URL. When you URL decode a string, you reverse the process.
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. Those methods replace special characters with URL-safe sequences.
The string extension methods are really easy to use. This example uses them in the following code.
private void btnConvert_Click(object sender, EventArgs e)
{
txtNbsp.Text = txtString.Text.SpaceToNbsp();
txtUrlEncode.Text = txtString.Text.UrlEncode();
txtUrlDecode.Text = txtUrlEncode.Text.UrlDecode();
}
Download the example to experiment with it and to see additional details.
|