Mohanapriya R Mohanapriya R
Updated date Apr 08, 2024
In this article, we will learn how to decode HTML-encoded strings in C#. The article provides a clear explanation of HTML encoding, a simple C# program using System.Net.WebUtility, and a hands-on example with output.
  • 2.9k
  • 0
  • 0

HTML Encoding:

HTML encoding replaces special characters with their corresponding HTML entities. For instance, the less-than sign < becomes &lt;, and the greater-than sign > becomes &gt;. This is important to prevent browsers from interpreting these characters as part of the HTML markup.

Decoding HTML Encoded Strings in C#:

To convert HTML-encoded strings back to their normal form in C#, you can leverage the System.Net.WebUtility class, specifically the HtmlDecode method. This method is designed to handle HTML-encoded strings and reverse the encoding process.

using System;

class Program
{
    static void Main()
    {
        string encodedString = "Hello &lt;world&gt;!";
        string decodedString = System.Net.WebUtility.HtmlDecode(encodedString);

        Console.WriteLine("Encoded String: " + encodedString);
        Console.WriteLine("Decoded String: " + decodedString);
    }
}
  • We declare a string encodedString containing an HTML-encoded message.
  • We use System.Net.WebUtility.HtmlDecode to decode the HTML-encoded string, storing the result in decodedString.
  • Finally, we print both the original encoded string and the decoded string.

Output:

Encoded String: Hello &lt;world&gt;!
Decoded String: Hello <world>!

The output illustrates the conversion of the HTML-encoded string back to its normal form.

Comments (0)

There are no comments. Be the first to comment!!!