c#:将网页的html源码读入字符串

时间:2010-04-12 21:33:33

标签: c#

我希望能够使用winforms将某个网页的html源读入c#中的字符串

我该怎么做?

3 个答案:

答案 0 :(得分:24)

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

现在使用C#5中的async / await hotness

string html = await new WebClient().DownloadStringTaskAsync("http://github.com");

答案 1 :(得分:10)

查看WebClient.DownloadString

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

您可以使用WebClient.DownloadStringAsyncBackgroundWorker下载文件,而不会阻止用户界面。

答案 2 :(得分:4)

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);