Generate HTML File using C#

Here, I am going to explain how to generate html file from code behind. Using this article, you can generate HTML file from code behind on specified location. Here we are going to use main two C# classes to generate HTML file.

  • StringBuilder: Using StringBuilder, we can create mutable object of string. Here we are appending HTML content to it.
  • StreamWriter: Using StreamWriter, we can create a new file and write content to it, which is appended to StringBuilder.

Using below code, we can generate an HTML file from the c# code. It is useful when we want to generate HTML document by replacing dynamic value.

Following steps are needed to follow for generating an HTML file from code behind.

1. Add the necessary namespace to resolve dependency of the classes and objects used in coding.

using System;  
using System.Collections.Generic;  
using System.IO; using System.Linq;  
using System.Text;  using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;

2. Create StringBuilder Object to append HTML content.

StringBuilder sb = new StringBuilder();

3. Append HTML content in StringBuilder object.

sb.Append("<html><head><meta charset='utf-8'/>"); 
sb.Append("<style>ul li{list-style:none;margin-top:3px;margin-bottom:3px;}"); 
sb.Append("h1{font-size: 23px;margin-bottom: 0px;margin-top: 0px;");
sb.Append("font-weight: normal;font-family: Arial;}"); 
sb.Append("h2{margin: 3px;margin-left: 0px;font-size: 16px;}"); 
sb.Append("h3{margin: 3px;font-size: 16px;}"); 
sb.Append("h4{margin: 3px;margin-left: 0px;font-size: 13px;}"); 
sb.Append("h5{margin: 3px;font-size: 11px;font-weight: normal;font-family: Arial;}"); 
sb.Append("</style>");
sb.Append("</head>"); 
sb.Append("<body style='text-align: center;margin:auto;margin-top:0px;margin-bottom:5px;'>"); 
sb.Append("Hello !");
sb.Append("</body>");
sb.Append("</html>

4. Create StreamWriter object and pass location and name of the file, here, we are taking a blank HTML file, and after that, we append the HTML at runtime in our file.  

StreamWriter sw1 = new StreamWriter(@"C:\Users\Alpesh.Maniya\Desktop\TestDocs.html");

5. Write HTML content to file. 

sw1.Write(sb); 

6. Flush, Close, and Dispose the object once file writing has been done. 

sw1.Flush();  
sw1.Close();  
sw1.Dispose(); 

Now check the file that is created from the code. You will find the file with HTML content.