IMG-LOGO

How to get Html Source Code using WebRequest Object in ASP.Net C#?

andy - 04 Aug, 2013 6430 Views 0 Comment

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");
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.