Monday, December 18, 2006

saving an html file from a code behind - ASP.NET

However if you really need to generate HTML output from an ASPX page it canbe easily done by overriding the Render method and capturing the output from


Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

' *** Write the HTML into this string builder

Dim sb As StringBuilder = New StringBuilder()

Dim hWriter As HtmlTextWriter = New HtmlTextWriter(New StringWriter(sb)) MyBase.Render(hWriter)

' *** store to a string Dim PageResult As String = sb.ToString()

' *** Write it back to the server's HTTP Stream -

' *** skip this if you don't want to display the rendered content writer.Write(PageResult)

.... PageResult now hold the HTML content you can write to diskdo whatever you want to with.

End Sub

This example goes to string but you can use a StreamWriter instead of stringbuilder to dump the output directly to file if you wish.


Same in C#:


protected override void Render(HtmlTextWriter writer)
{
// *** Write the HTML into this string builder
StringBuilder sb = new StringBuilder();
HtmlTextWriter hWriter = new HtmlTextWriter(new StringWriter(sb));
base.Render(hWriter);
// *** store to a string
string PageResult = sb.ToString();
// *** Write it back to the server's HTTP Stream -// *** skip this if you don't want to display the rendered content
writer.Write(PageResult);
.... PageResult now hold the HTML content you can write out to diskdo whatever you want to with.
}

3 comments:

Gerin Jacob said...

I have a list of select queries which I need to execute in oracle database, and i need to save the results of all these queries into a single html page in table format. And these html file should be saved to disk, how can I save this to a html file in the disk?

Keviv said...

Hi Gerin,

Check out this post in my blog
http://vivekthangaswamy.blogspot.com/2007/02/generate-html-file-as-output-of.html

You will a idea how solve your problem.

Regards
Vivek.T

Unknown said...

I have webfrom1.aspx page with 6 frames to generate pie chart .these 6 frames call same page "Visual.aspx",and same stored procedure with differnt parameters with the help of Querystrings.I need to save the result(pie chart in html format).

ASP.NET MVC - Sport Facility Booking system

  The project relies on some external service providers. Thus accessing them via their API requires authentication. An API Key need to be su...