Mohanapriya R Mohanapriya R
Updated date Jun 17, 2024
In this article, we will learn how to convert plain text to HTML using C# for better web content formatting.
  • 1.5k
  • 0
  • 0

Why Convert Plain Text to HTML?

Plain text lacks formatting such as bold, italics, and headings which are important for creating web content or pages. By converting plain text to HTML, we can add these formatting elements and enhance the appearance of our content on the website.

We will use a simple C# program that converts simple plain text input into HTML format. 

using System;

class Program
{
    static void Main()
    {
        string plainText = "Welcome to TechieHook website. Let's convert it to <b>HTML</b>!";
        string htmlText = ConvertToHtml(plainText);
        Console.WriteLine(htmlText);  
        Console.ReadKey();
    }

    static string ConvertToHtml(string plainText)
    {
        // Replace special characters with HTML entities
        string htmlText = System.Web.HttpUtility.HtmlEncode(plainText);
        // Wrap plain text in <p> tag
        htmlText = $"<p>{htmlText}</p>";
        return htmlText;
    }
}

We defined a string plainText that contains our plain text content. The ConvertToHtml method takes the plain text as input and returns the HTML formatted text. We used HtmlEncode method from System.Web.HttpUtility to replace special characters with their HTML entities to prevent XSS attacks. Then, we wrapped the plain text content in <p> tags to mentioned it as a paragraph.

Output:

<p>Welcome to TechieHook website. Let&#39;s convert it to &lt;b&gt;HTML&lt;/b&gt;!</p>

Comments (0)

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