How to Create HTML File in C#

Automated generation and processing of HTML documents is now becoming a demanding feature. Different reports and invoices are now being generated dynamically in HTML format. This topic will cover basic implementation of HTML automation within .NET Applications. So, you will be learning how to create HTML file in C#.

Steps to Create HTML File in C#

  1. Open Visual Studio and Create an Empty Console Application
  2. Add a reference to Aspose.HTML for .NET from NuGet.org
  3. Use default HTMLDocument() constructor to create an empty HTML document
  4. Create a text element using CreateTextNode() method
  5. Append created text to the body of the HTML document
  6. Save the HTML file to disk

Once you have successfully installed Aspose.HTML for .NET from NuGet Gallery, you will be able to access the Classes and Methods of the API. You need to create an empty HTML document by using the HTMLDocument() constructor without any parameters. Once an HTML document is initialized, you will be able to add different elements to it. In the below code snippet, a simple text element is being added to the body using C# to generate HTML document.

Code to Create HTML File in C#

using System;
using System.IO;
// Add reference to Aspose.HTML for .NET API
// Use following namespace to create HTML file
using Aspose.Html;
namespace CreateHTMLFiles
{
class Program
{
static void Main(string[] args)
{
// Set license before generating HTML file
Aspose.Html.License AsposeHTMLLicense = new Aspose.Html.License();
AsposeHTMLLicense.SetLicense(@"c:\asposelicense\license.lic");
string outFile = @"c:\Created_HTML_File.html";
// Initialize an empty HTML document
using (var htmldocument = new HTMLDocument())
{
// Create a text element to add to the HTML document
var text = htmldocument.CreateTextNode("This HTML document is generated by Aspose.HTML for .NET using C#.");
// Add text element to HTML body
htmldocument.Body.AppendChild(text);
// Save the HTML file to a disk
htmldocument.Save(outFile);
}
}
}
}

In the previous topic, you have learnt how to convert Markdown to XPS in C#. You can use the above simple and self-explanatory code snippet to generate HTML file in C#. Once the HTML file is generated, you can open and view it in any browser to display the information that needs to be showcased.

 English