HtmlEncode in ASP.NET

I keep forgetting where to find HtmlEncode when working in .NET. I end up going to Google and doing a couple searches before I find the right namespace to include. Hopefully now I’ll remember to look at my blog rather than Google :-)

HtmlEncode does exactly what it sounds like it should. It takes a string value as a parameter, and returns an escaped string.

using System.Web;

private static string ReturnEncoded()
{
	return (HttpUtility.HtmlEncode("<br />"));
}

This function would return “&lt;br /&gt;”. Not a real useful function, but is shows how to use HtmlEncode.

This same location also has HtmlDecode, UrlEncode, and UrlDecode.

1 Comment so far

  1. fordareh on May 28, 2008

    I was working on a command line C# executable and couldn’t find out for the life of me how to get some sort of an HttpServerUtility object. I didn’t realize that HttpUtility existed.

    Thanks!

Leave a reply