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.
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 > .
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.
HtmlEncode – makes it safe to display user-entered text on a web page. < and > are turned into < and > 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With