I am working in an asp.net website. I need to get the current page HTML output in the Page Load event. I tried the following code. But I am not getting any output, it executes continuously.
protected void Page_Load(object sender, EventArgs e)
{
Http(Request.Url.ToString());
}
public void Http(string url)
{
if (url.Length > 0)
{
Uri myUri = new Uri(url);
// Create a 'HttpWebRequest' object for the specified url.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
// Set the user agent as if we were a web browser
myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var stream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(stream);
var html = reader.ReadToEnd();
// Release resources of response object.
myHttpWebResponse.Close();
Response.Write(html);
}
}
What is wrong here?
Is there is any other way to get current page HTML output using c#?
I tried the following code also:
protected void Page_Load(object sender, EventArgs e)
{
Page pp = this.Page;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
pp.RenderControl(hw);
string theOut = tw.ToString().Trim();
string FilePath = @"D:\Home.txt";
Stream s = new FileStream(FilePath, FileMode.Create);
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(theOut);
sw.Close();
}
By using the code i am able to get the HTML in the ".txt" file.But execution of this code causes "A page can have only one server-side Form tag." error. Can anybody help me to solve this?