Mohanapriya R Mohanapriya R
Updated date Feb 15, 2024
In this article, we will learn how to convert plain text to HTML using C# for better web content formatting.

Why Convert Plain Text to HTML?

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

We will use C# to write a simple program that takes plain text input and converts it into HTML format. We'll utilize basic string manipulation techniques to achieve this.

Below is the C# code for converting plain text to HTML:

using System;

class Program
    static void Main()
        string plainText = "This is a plain text. Let's convert it to <b>HTML</b>!";
        string htmlText = ConvertToHtml(plainText);

    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;


The output of the above program will be:

<p>This is a plain text. Let's convert it to &lt;b&gt;HTML&lt;/b&gt;!</p>
  • We start by defining a string plainText containing our plain text content.
  • The ConvertToHtml method takes the plain text as input and returns the HTML formatted text.
  • We use HtmlEncode method from System.Web.HttpUtility to replace special characters with their HTML entities to prevent XSS attacks.
  • Finally, we wrap the plain text content in <p> tags to denote it as a paragraph.

Comments (0)

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