Tuesday, May 4, 2010

Convert Asp.Net page to HTML

Solution:

The appropriate namespaces to be used here would be

System.Net which have classes WebRequest and WebResponse.

* WebRequest is the abstact base class for the .NET Framework's request/response model for accessing data from the internet and
* WebResponse is the abstract base class from which protocol specific response classes are derived.

System.IO which have classes StreamReader and StreamWriter.

* StreamReader designed for character input in a particular encoding.
* StreamWriter designed for character output in a particular encoding.

Code:

C#

WebRequest mywebReq ;
WebResponse mywebResp ;
StreamReader sr ;
string strHTML ;
StreamWriter sw;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
mywebReq = WebRequest.Create("ASPX PAGE WITH FULL PATH");
mywebResp = mywebReq.GetResponse();
sr = new StreamReader(mywebResp.GetResponseStream());
strHTML = sr.ReadToEnd();
sw = File.CreateText(Server.MapPath("temp.html"));
sw.WriteLine(strHTML);
sw.Close();
Response.WriteFile(Server.MapPath("temp.html"));
}

Note :
For creating the file (in above case "temp.html") give appropriate rights (modify and write) to the ASPNET user.

To specify the Encoding specify the second parameter of the StreamReader accordingly in the c# You need to write :

sr = new StreamReader(mywebResp.GetResponseStream(), System.Text.Encoding.ASCII);