ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

HttpUtility Helpers

Make easily accessible some functions available in HttpUtility into an Extension.

Source

using System.Collections.Specialized;
using System.Web;

namespace MyConsoleTester
{
    public static class HttpEx
    {
        public static string HtmlEncode(this string data)
        {
            return HttpUtility.HtmlEncode(data);
        }

        public static string HtmlDecode(this string data)
        {
            return HttpUtility.HtmlDecode(data);
        }

        public static NameValueCollection ParseQueryString(this string query)
        {
            return HttpUtility.ParseQueryString(query);
        }

        public static string UrlEncode(this string url)
        {
            return HttpUtility.UrlEncode(url);
        }

        public static string UrlDecode(this string url)
        {
            return HttpUtility.UrlDecode(url);            
        }

        public static string UrlPathEncode(this string url)
        {
            return HttpUtility.UrlPathEncode(url);
        }
    }
}

Example

string html = "<title>this is the Test Title</title>";
string url = "http://www.domain.com?q=test&a=123&g=test";

Console.WriteLine("UrlEncode: {0}", url.UrlEncode());
Console.WriteLine("UrlDecode: {0}", url.UrlDecode());
Console.WriteLine("UrlPathEncode: {0}", url.UrlPathEncode());
Console.WriteLine("HtmlEncode: {0}", html.HtmlEncode());
Console.WriteLine("HtmlDecode: {0}", html.HtmlDecode());

int idx = url.IndexOf('?');
String querystring = null;
if (idx >= 0)
{
	querystring = (idx < url.Length - 1) ? url.Substring(idx + 1) : String.Empty;
}

System.Collections.Specialized.NameValueCollection coll = querystring.ParseQueryString();
Console.WriteLine("   [INDEX] KEY        VALUE");
for (int i = 0; i < coll.Count; i++)
	Console.WriteLine("   [{0}]     {1,-10} {2}", i, coll.GetKey(i), coll.Get(i));

Author: Earljon Hidalgo

Submitted on: 23 apr. 2008

Language: C#

Type: System.String

Views: 11525