3. March 2011 09:58
I received an email from Jeff W. the other day, and he had an interesting requirement.
He wanted to save the current contents of the ASP.NET page, to a MHT document.
This is a little different than the normal situation, because normally aspNetMHT is pointed at a Url, and the remote Url is downloaded, and converted to the MHT document.
In this particular scenario, Jeff wanted to save the contents of the ASP.NET page being rendered, from inside of the page. It turns out this is possible by accessing the ASP.NET Page Render event. If you override the current Render event, with the code below, you can save the current contents, and convert them to a MHT documents.
As always, if anyone has any questions, feel free to contact me through the Contact Us page.
protected override void Render(HtmlTextWriter writer)
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter localWriter = new HtmlTextWriter(sw);
//get the contets of the page
string html = sw.ToString();
//check to see if the page was posted
if( Page.IsPostBack )
//save it to a MHT file
MHT m = new MHT();
//this is the url of this page. It's used so aspNetMHT can resolve any images.
//this need to be modified to match your page name.
string url = "http://localhost/mhttest/CurrentPage.aspx";
m.LoadString( html, url );
//save the MHT to the filesystem
string path = "c:\\temp\\" + DateTime.Now.ToFileTime().ToString() + "_sample.mht";
m.SaveToFile( path );
//continue sending the html to the browser
Protected Overrides Sub Render(writer As HtmlTextWriter)
Dim sw As New System.IO.StringWriter()
Dim localWriter As New HtmlTextWriter(sw)
'get the contets of the page
Dim html As String = sw.ToString()
'check to see if the page was posted
If Page.IsPostBack Then
'save it to a MHT file
Dim m As New MHT()
'this is the url of this page. It's used so aspNetMHT can resolve any images.
'this needs to be modified to match your page name.
Dim url As String = "http://localhost/mhttest/CurrentPage.aspx"
'save the MHT to the filesystem
Dim path As String = "c:\temp\" + DateTime.Now.ToFileTime().ToString() + "_sample.mht"
'continue sending the html to the browser
End Sub 'Render