Mohanapriya R Mohanapriya R
Updated date Feb 01, 2024
In this article, we will learn how to decode HTML-encoded strings in C# using the WebUtility class. This article provides a simple program to showcase the conversion process, ensuring your web-related tasks are seamlessly executed.

Introduction:

In the world of web development, dealing with HTML-encoded strings is a common task. HTML-encoded strings contain special characters represented by entities, such as "<" for < and "&" for &. In C#, it's crucial to convert these encoded strings back to their normal form for proper display and processing. In this article, we will explore the process of decoding HTML entities in C#.

Decoding HTML Entities in C#:

C# provides a handy class named System.Net.WebUtility that includes the HtmlDecode method, which helps in decoding HTML-encoded strings. Let's take a look at a simple program that demonstrates how to use this method:

using System;

class Program
{
    static void Main()
    {
        // HTML-encoded string
        string encodedString = "Hello &lt;world&gt;! This &amp; is a test.";

        // Decoding the HTML-encoded string
        string decodedString = System.Net.WebUtility.HtmlDecode(encodedString);

        // Displaying the decoded string
        Console.WriteLine("Decoded String: " + decodedString);
    }
}

Output:

Decoded String: Hello <world>! This & is a test.

In this program, we start with an HTML-encoded string (encodedString) containing entities like "<" and "&". We then use the HtmlDecode method from System.Net.WebUtility to convert this encoded string into a normal string (decodedString). Finally, we print the decoded string to the console.

Conclusion:

Decoding HTML entities is a crucial step in handling HTML content in C#. The System.Net.WebUtility.HtmlDecode method simplifies this process by providing a convenient way to convert encoded strings back to their original form. 

Comments (0)

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