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 “<br />”. Not a real useful function, but is shows how to use HtmlEncode.
This same location also has HtmlDecode, UrlEncode, and UrlDecode.
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!
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);
else
return (HttpUtility.HtmlEncode (s));
}
}
Andrew – Thanks for the comment, and the code sample. Looks very useful!
>> 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.