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.


4 comments so far

  1. fordareh on

    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.


  2. Andrew Webb on

    With C# 3.0 extension methods you can have the HtmlEncode method as part of the String class…

    // Extension methods for the ‘String’ class.
    public static class StringExtensions
    // Returns the HTML-encoded version of the specified string.
    public static String HtmlEncode (this String s)
    if (String.IsNullOrEmpty (s))
    return (s);
    return (HttpUtility.HtmlEncode (s));

  3. Brian Webster on

    Andrew – Thanks for the comment, and the code sample. Looks very useful!

  4. R. Schreurs on

    >> Hopefully now I’ll remember to look at my blog rather than Google:-)

    Even better: Google lists this blog on top. Now there is nothing I need to remember 🙂

    Thanks for blogging this.

Comments are closed.

%d bloggers like this: