tags:

views:

3845

answers:

5

Hello,

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?

Thank you!

+18  A: 

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);
Russ Bradberry
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
duly noted, and edited
Russ Bradberry
capitalization matters: HtmlEncode
Nathan
+2  A: 

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

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

Irwin
See comment to Russ
AnthonyWJones
+4  A: 

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

AnthonyWJones
+11  A: 

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
very elegant, nice.
Russ Bradberry
+4  A: 

http://msdn.microsoft.com/en-us/library/system.net.webutility.aspx available in .NET 4 (No need to reference System.Web.dll)

George Chakhidze
Thanks, Now I can use the .NET 4 Client Profile instead of the full framework!
Coderuckus