Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlEncode from Class Library

Tags:

c#

html-encode

People also ask

What is HtmlEncode C#?

HtmlEncode(Object)Converts an object's string representation into an HTML-encoded string, and returns the encoded string. public: static System::String ^ HtmlEncode(System::Object ^ value); C# Copy.

When should I use HtmlEncode?

Any time you are trying to output data that could include untrusted html, you should use HTMLENCODE . Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign ( > ), with HTML entity equivalents, such as > .

What is the use of HtmlEncode?

The HTMLEncode method applies HTML encoding to a specified string. This is useful as a quick method of encoding form data and other client request data before using it in your Web application. Encoding data converts potentially unsafe characters to their HTML-encoded equivalent.

What is the difference between HtmlEncode and URLEncode?

HtmlEncode – makes it safe to display user-entered text on a web page. < and > are turned into &lt; and &gt; UrlEncode – makes it safe to work as a url. is turned into + and a bunch more. “If you're wondering which one you should use in an HTTP POST, well just think of POST data as an extremely long query string.


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

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


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