176

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Villager
  • 6,569
  • 22
  • 65
  • 87

8 Answers8

214

System.Net.WebUtility class is available starting from .NET Framework 4.0 — you donʼt need System.Web dependency.

Giorgi Chakhidze
  • 3,351
  • 3
  • 22
  • 19
212

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);
Doctor Jones
  • 21,196
  • 13
  • 77
  • 99
Russ Bradberry
  • 10,705
  • 17
  • 69
  • 85
  • 8
    You need to create an instance of the Server Utility class which is designed to support a current in progress Request and emulate features the old ASP Server object. HttpUtility is a lighter weight set of Static methods. – AnthonyWJones Jul 17 '09 at 17:11
  • 3
    Make sure that your framework type does not specify "Client Profile". Changes this to the full framework and you'll have the system.web assembly available – Martin Murphy Feb 29 '12 at 16:40
  • 3
    System.Web.HttpUtility was not available in my project (.NET Framework 4.7.1). System.Net.WebUtility.HtmlEncode(string) was available and worked fine. – Kappacake Jul 04 '19 at 09:05
41

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();
Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
28

Try this

System.Net.WebUtility.HtmlDecode(string);
System.Net.WebUtility.HtmlEncode(string);
Palanikumar
  • 6,940
  • 4
  • 40
  • 51
  • 4
    This is much better because I don't have to add reference to System.Web in my WPF project. – newman Mar 14 '13 at 04:13
7

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

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
3

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

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

Irwin
  • 12,551
  • 11
  • 67
  • 97
3

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);
Koen Zomers
  • 4,236
  • 1
  • 22
  • 14
2

In case you are working with silverlight, use this:

System.Windows.Browser.HttpUtility.HtmlEncode(...);
Jonx
  • 1,075
  • 12
  • 16