tags:

views:

1028

answers:

3

How to retrieve a webpage and diplay the html to the console with C# ?

+18  A: 

Use the System.Net.WebClient class.

System.Console.WriteLine(new System.Net.WebClient().DownloadString(url));
Mehrdad Afshari
Nice!! :-) +1 from me! Straight to the point!
REA_ANDREW
It would be synchronous, though. Meaning it will only display data after the entire page has been loaded.
configurator
Sexy one liner... sold! +1
Duke of Muppets
+11  A: 

I have knocked up an example:

WebRequest r = WebRequest.Create("http://www.msn.com");
WebResponse resp = r.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    Console.WriteLine(sr.ReadToEnd());
}

Console.ReadKey();

Here is another option, using the WebClient this time and do it asynchronously:

static void Main(string[] args)
{
    System.Net.WebClient c = new WebClient();
    c.DownloadDataCompleted += 
         new DownloadDataCompletedEventHandler(c_DownloadDataCompleted);
    c.DownloadDataAsync(new Uri("http://www.msn.com"));

    Console.ReadKey();
}

static void c_DownloadDataCompleted(object sender, 
                                    DownloadDataCompletedEventArgs e)
{
    Console.WriteLine(Encoding.ASCII.GetString(e.Result));
}

The second option is handy as it will not block the UI Thread, giving a better experience.

REA_ANDREW
The UI thread? Isn't this a console app?
Mehrdad Afshari
I did not specify that my example was for the sole purposes of using with a console application.
REA_ANDREW
I agree but I think the exact example you mentioned demonstrate something specifically *wrong* (in console version only): pressing a key before the URL is fetched causes the console to be closed before anything is written to it. Changing the name of `Main` method better demonstrates your intention.
Mehrdad Afshari
It was just to convey the example of the Async mehtod option. Fair do's I could have extracted the method into its own I suppose. Either way, I just did it quick to get my example out there. I had no intention that "pressing a key" helped get the html of the request. Apologies for the confusion.
REA_ANDREW
That's Fine :) Sorry if this bothered you. I didn't mean it.
Mehrdad Afshari
no no, discussion is good :-)
REA_ANDREW
+1 for the more complete code.
RoadWarrior
+1  A: 
// Save HTML code to a local file.
WebClient client = new WebClient ();
client.DownloadFile("http://yoursite.com/page.html", @"C:\htmlFile.html");

// Without saving it.
string htmlCode = client.DownloadString("http://yoursite.com/page.html");
Ahmed