11

I would like to be able to read the html source of a certain webpage into a string in c# using winforms

how do I do this?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

3 Answers3

25
string html = new WebClient().DownloadString("http://twitter.com");

And now with async/await hotness in C# 5

string html = await new WebClient().DownloadStringTaskAsync("http://github.com");
Joel Martinez
  • 46,929
  • 26
  • 130
  • 185
  • I get Error "; expected" on that second line. I use VS2012 but it seems that await doesn't work. If I try string html = await wc.DownloadStringTaskAsync("link"); I get: "Error 1 The 'await' operator can only be used within an async method..." Do I need to add some reference to the project? – grabah Apr 05 '13 at 09:56
  • 1
    I don't intend this response to sound like snark, although I understand it may come across that way; but the error message says exactly what the resolution is :) the method that contains that line has to be decorated with the "async" keyword. – Joel Martinez Apr 05 '13 at 15:02
10

Have a look at WebClient.DownloadString:

using (WebClient wc = new WebClient())
{
    string html = wc.DownloadString(address);
}

You can use WebClient.DownloadStringAsync or a BackgroundWorker to download the file without blocking the UI.

dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    Webclient is an IDisposable, so don't forget the `using` block. – Joel Coehoorn Apr 12 '10 at 21:36
  • joel can u explain that comment to me please – Alex Gordon Apr 12 '10 at 21:59
  • @every_answer_gets_a_point: Joel Coehoorn is referring to the `using` block which is present in my answer, but not in the answer of Joel Martinez. Since WebClient implements the IDisposable interface, the `using` block should be present. – dtb Apr 12 '10 at 22:19
3
var req = WebRequest.Create("http://www.dannythorpe.com");
req.BeginGetResponse(r =>
{
    var response = req.EndGetResponse(r);
    var stream = response.GetResponseStream();
    var reader = new StreamReader(stream, true);
    var str = reader.ReadToEnd();
    Console.WriteLine(str);
}, null);
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
dthorpe
  • 35,318
  • 5
  • 75
  • 119
  • thank you, but why dont you think joel's response is good? – Alex Gordon Apr 12 '10 at 21:48
  • 2
    I have no opinion of Joel's solution. Never heard of WebClient.DownloadString before this post. This is the code I use. WebClient.DownloadString looks simpler to use, but may not provide the same level of control (error handling, etc) as doing the separate steps yourself. (Joel and I composed and posted simultaneously) – dthorpe Apr 12 '10 at 23:04