How to Create Dynamic HTML Document from VB.NET?

Generally while designing a CMS we found this situation to handle. Let us assume we have records in Database. From those records we required to Create HTML pages dynamically. Here I did the same using VB.NET File Operations.

Look at the below Codes from my Code behind file. Here I have 2 functions & page load event. During page load I am calling the function CreatePage(). CreatePage function accepts 3 parameters page title, HTML text here I mean contents for HTML page & The file name I want to create physically.

Inside CreatePage function I am concatenating a string with HTML format. In head tag I am adding the page title. Then entering a new-line character. Similarly did for title & body content. Not doing the File Operations here. For file operation I have one more separate function SaveTextToFile(). SaveTextToFile accepts 2 parameters. First parameter is the HTML string we concatenating in CreatePage function. Second one is the file path. File path means where to Create the HTML page.

To Create file physically here I referred System.IO & StreamWriter method. After Create Instance I am using Write method. Including this I have a boolean variable. Which helps to know whether the file created successfully or not. This variable default value is false. Just after StreamWriter Write method I am updating this variable.

Create Dynamic HTML document from VB.NET

Imports System.IO

Partial Class _CreateHtml
Inherits System.Web.UI.Page

Public Sub CreatePage(ByVal HTMLTitle As String, ByVal HTMLText As String, ByVal HTMLFileName As String)
Dim strFile As String
strFile = ""
'Constructing the String strFile
strFile = "<html>" & vbNewLine
strFile = strFile & "<head>" & vbNewLine
strFile = strFile & "<title>" & HTMLTitle & "</title>" & vbNewLine
strFile = strFile & "</head><body>" & vbNewLine
strFile = strFile & HTMLText & vbNewLine
strFile = strFile & "</body></html>"
'Calling SaveTextToFile function for IO Operation
SaveTextToFile(strFile, Server.MapPath(".") & "\HTMLFiles\" & HTMLFileName & ".html")
End Sub

Public Function SaveTextToFile(ByVal strData As String, ByVal FullPath As String, Optional ByVal ErrInfo As String = "") As Boolean
Dim Contents As String
Dim Saved As Boolean = False
'Using StreamWriter to Create File
Dim objReader As IO.StreamWriter
Try
objReader = New IO.StreamWriter(FullPath)
objReader.Write(strData)
objReader.Close()
Saved = True
Catch Ex As Exception
Response.Write(Ex.Message)
End Try
Return Saved
End Function

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
CreatePage("Title goes here", "Hello world! This is a HTML file Created from Code Behind.", "Sample")
End Sub
End Class