Mohanapriya R Mohanapriya R
Updated date Jul 12, 2024
In this article, we will learn how to convert string to HTML encode in C#.
  • 3.1k
  • 0
  • 0

Understanding HTML Encoding:

HTML encoding is the process of converting special characters into their corresponding HTML entities. This is essential when displaying user-generated content on a web page to prevent the interpretation of input as executable code. For instance, the less-than symbol < is encoded as &lt;, and the greater-than symbol > is encoded as &gt;.

using System;
using System.Web;

class Program
{
    static void Main()
    {
        // Input string with special characters
        string userInput = "<h1>Welcome to TechieHooK!</h1>";

        // HTML encode the string
        string encodedString = HttpUtility.HtmlEncode(userInput);

        // Display the original and encoded strings
        Console.WriteLine("Original String: " + userInput);
        Console.WriteLine("Encoded String: " + encodedString);
        Console.ReadKey();
    }
}

We started with a sample string containing HTML tags. The HttpUtility.HtmlEncode method is then applied to encode the string. 

Output:

Original String: <h1>Welcome to TechieHooK!</h1>
Encoded String: &lt;h1&gt;Welcome to TechieHooK!&lt;/h1&gt;

Comments (0)

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