Get HTML code from website in C#

ggcodes picture ggcodes · May 20, 2013 · Viewed 317.3k times · Source

How to get the HTML code from a website, save it, and find some text by a LINQ expression?

I'm using the following code to get the source of a web page:

public static String code(string Url)
{
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
    myRequest.Method = "GET";
    WebResponse myResponse = myRequest.GetResponse();
    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
    string result = sr.ReadToEnd();
    sr.Close();
    myResponse.Close();

    return result;
 }

How do I find the text in a div in the source of the web page?

Answer

Santosh Panda picture Santosh Panda · May 20, 2013

Better you can use the Webclient class to simplify your task:

using System.Net;

using (WebClient client = new WebClient())
{
    string htmlCode = client.DownloadString("http://somesite.com/default.html");
}