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
2009-02-28 14:34:55
Nice!! :-) +1 from me! Straight to the point!
REA_ANDREW
2009-02-28 14:44:18
It would be synchronous, though. Meaning it will only display data after the entire page has been loaded.
configurator
2009-02-28 15:34:57
Sexy one liner... sold! +1
Duke of Muppets
2009-02-28 15:51:08
+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
2009-02-28 14:38:05
I did not specify that my example was for the sole purposes of using with a console application.
REA_ANDREW
2009-02-28 15:08:20
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
2009-02-28 15:23:57
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
2009-02-28 15:37:38
+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
2009-03-01 07:37:11