[c#] HtmlEncode from Class Library

I have a class library (in C#). I need to encode my data using the HtmlEncode method. This is easy to do from a web application. My question is, how do I use this method from a class library that is being called from a console application?

This question is related to c# html-encode

The answer is


System.Net.WebUtility class is available starting from .NET 4.0 (You don't need System.Web.dll dependency).


In case you are working with silverlight, use this:

System.Windows.Browser.HttpUtility.HtmlEncode(...);

In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:

Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class


Just reference the System.Web assembly and then call: HttpServerUtility.HtmlEncode

http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx


Try this

System.Net.WebUtility.HtmlDecode(string);
System.Net.WebUtility.HtmlEncode(string);