Answers:
您可以使用WebClient类下载文件:
using System.Net;
using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");
// Or you can get the file content without saving it
string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}
基本上:
using System.Net;
using System.Net.Http; // in LINQPad, also add a reference to System.Net.Http.dll
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
Console.WriteLine(source);
最新,最新的答案
这篇文章确实很老(我回答时已经7岁了),因此其他答案中没有一个使用新的推荐方法,即HttpClient上课。
HttpClient被认为是新的API,并且应替换旧的API(WebClient和WebRequest)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
有关如何使用HttpClient该类的更多信息(尤其是在异步情况下),您可以参考此问题
您可以通过以下方式获得它:
var html = new System.Net.WebClient().DownloadString(siteUrl)
Dispose是WebClient吗?
MS网站上建议使用@cms方法,但是我有一个很难解决的问题,两种方法都发布在这里,现在我发布所有解决方案!
问题:
如果您使用这样的网址:www.somesite.it/?p=1500在某些情况下,您会收到内部服务器错误(500),尽管在Web浏览器中可以www.somesite.it/?p=1500正常工作。
解决方案: 您必须移出参数,工作代码为:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}