2009-03-01 45 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