Home
Manage Your Code
Snippet: Get HTML Page source from given URL (C#)
Title: Get HTML Page source from given URL Language: C#
Description: This code is used to get HTML source code of any given URL. Views: 95
Author: Dhaval Patel Date Added: 5/6/2008
Copy Code  
1public static string GetHtmlPageSource(string url, string username, string password)
2    {
3        System.IO.Stream st = null;
4        System.IO.StreamReader sr = null;
5        try
6        {
7            // make a Web request
8            System.Net.WebRequest req = System.Net.WebRequest.Create(url);
9            // if the username/password are specified, use these credentials
10            if (username != null && password != null)
11                req.Credentials = new System.Net.NetworkCredential(username, password);
12            // get the response and read from the result stream
13            System.Net.WebResponse resp = req.GetResponse();
14            st = resp.GetResponseStream();
15            sr = new System.IO.StreamReader(st);
16            // read all the text in it
17            return sr.ReadToEnd();
18        }
19        catch (Exception ex)
20        {
21            return string.Empty;
22        }
23        finally
24        {
25            // always close readers and streams
26            sr.Close();
27            st.Close();
28        }
29    }