This tutorial will show you how you can use WebRequest object to read or get html source from a website page in C#.
//required .net objects using System.Net; using System.IO;
// A GetWebHtmlSourceCode function that will return the html source code from a url page public static string GetWebHtmlSourceCode(string url) { string content = ""; StreamReader objStreamReader = default(StreamReader); WebRequest objWebRequest = default(WebRequest); WebResponse objWebResponse = default(WebResponse); try { objWebRequest = WebRequest.Create(url); objWebResponse = objWebRequest.GetResponse(); objStreamReader = new StreamReader(objWebResponse.GetResponseStream()); content = objStreamReader.ReadToEnd(); objStreamReader.Close(); } catch{ return content; } return content; }
// How to use this method protected void Page_Load(object sender, EventArgs e){ //Lets say we have a literal object called litResult litResult.Text = GetWebHtmlSourceCode("http://www.example.com"); }