HtmlEncode from Class Library

Viewed 135761

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?

8 Answers

Import System.Web Or call the System.Web.HttpUtility which contains it

You will need to add the reference to the DLL if it isn't there already

string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);

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();

Try this

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

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

In case you are working with silverlight, use this:

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