2009-03-01 40 views

回答

155

您可以用WebClient class下载文件:

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"); 
    //... 
} 
+0

应该注意:如果需要更多控制,请查看HttpWebRequest类(例如,能够指定身份验证)。 – Richard 2009-03-01 15:12:16

+1

是的,尽管你可以使用WebClient,使用client.UploadData(uriString,“POST”,postParamsByteArray)来执行POST请求,但HttpWebRequest为你提供了更多的控制。 – CMS 2009-03-01 17:51:31

33

基本上是:

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

“CMS” 的方式是比较近的,建议在MS网站

,但我有一个问题很难解决,宽度两个方法张贴在这里

现在我post solu所有!

问题: 如果使用这样的URL:在某些情况下,“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"); 
    //... 
} 

这里官方文档: http://msdn.microsoft.com/en-us/library/system.net.webclient.querystring.aspx

13

你可以得到它:

var html = new System.Net.WebClient().DownloadString(siteUrl) 
4

这篇文章真的很老了(当我7岁的时候回答它),所以没有其他解决方案使用新的推荐方式,即HttpClient类。

HttpClient被认为是新的API,它应该替换旧WebClientWebRequest

string url = "page url"; 

using (HttpClient client = new HttpClient()) 
{ 
    using (HttpResponseMessage response = client.GetAsync(url).Result) 
    { 
     using (HttpContent content = response.Content) 
     { 
      string result = content.ReadAsStringAsync().Result; 
     } 
    } 
} 

有关如何使用HttpClient类(特别是在异步的情况下)的更多信息,你可以参考this question