Get HTML Page source from given URL

CodeKeep C# Feed Maggio 7th, 2008

Description: This code is used to get HTML source code of any given URL.

Link: http://www.codekeep.net/snippets/85d76a91-5ab0-4580-9a56-065b971b97b6.aspx

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

  • .NET
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Comments are closed.

Trackback URI |