C# HtmlEncode and HtmlDecode

Hypertext markup language (HTML)

You know that HTML must be encoded to be displayed as text in another HTML document. With the WebUtility.HtmlEncode and WebUtility.HtmlDecode methods in the C# language, we can do this without writing any custom code.

This C# article shows how you can use the HtmlEncode and HtmlDecode methods.

Example

Let's look at an example of how you can use HtmlEncode and HtmlDecode in your C# program. Please notice that the System.Net assembly is included at the top of the program. The HtmlEncode method is designed to receive a string that contains HTML markup characters such as > and <. The HtmlDecode method, meanwhile, is designed to reverse those changes: it changes encoded characters back to actual HTML.

Program that uses HtmlEncode and HtmlDecode methods [C#]

using System;
using System.Net;

class Program
{
    static void Main()
    {
	string a = WebUtility.HtmlEncode("<html><head><title>T</title></head></html>");
	string b = WebUtility.HtmlDecode(a);

	Console.WriteLine("After HtmlEncode: " + a);
	Console.WriteLine("After HtmlDecode: " + b);
    }
}

Output

After HtmlEncode: &lt;html&gt;&lt;head&gt;&lt;title&gt;T&lt;/title&gt;&lt;/head&gt;&lt;/html&gt;
After HtmlDecode: <html><head><title>T</title></head></html>

Summary

.NET Framework information

These methods provide reliable replacement of HTML characters and are available in all your .NET programs. HtmlEncode and HtmlDecode also handle character entities: these are sequences such as &eacute; (é) that represent non-ASCII characters. These methods are also available on the HttpUtility type.

HttpUtility.HtmlEncode Methods HTML Articles
.NET