GetPageHTML – Get the HTML code for a given URL

GetPageHTML – C# code sample to get the HTML code for a given page URL

public class SampleCode 
{ 
    public SampleCode() 
    { }

    // Download the HTML source code at the specified URL
    // You can optionally specify the username/password credentials, 
    // in case the page uses Basic Authentication 
    // Returns a null string if any error occurs 
    public static string GetHtmlPageSource(string url) 
    { 
        return GetHtmlPageSource(url, null, null); 
    }

    public static string GetHtmlPageSource(string url, string username, string password)
    { 
        System.IO.Stream st = null; 
        System.IO.StreamReader sr = null;

        try
        { 
            // make a Web request 
            System.Net.WebRequest req = System.Net.WebRequest.Create(url);

            // if the username/password are specified, use these credentials 
            if (username != null && password != null) 
                req.Credentials = new System.Net.NetworkCredential(username, password);

            // get the response and read from the result stream 
            System.Net.WebResponse resp = req.GetResponse(); 
            st = resp.GetResponseStream(); 
            sr = new System.IO.StreamReader(st);

            // read all the text in it 
            return sr.ReadToEnd(); 
        } 
        catch (Exception ex) 
        { 
            return string.Empty; 
        } 
        finally 
        { 
            // always close readers and streams 
            sr.Close(); 
            st.Close(); 
        } 
    } 
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s