2012-08-09 140 views
1

我嘗試這樣做,我想,該網站的源內容將下載到的字符串:如何將網站內容下載到字符串?

public partial class Form1 : Form 
    { 
     WebClient client; 
     string url; 
     string[] Search(string SearchParameter); 


     public Form1() 
     { 
      InitializeComponent(); 

      url = "http://chatroll.com/rotternet"; 
      client = new WebClient(); 




      webBrowser1.Navigate("http://chatroll.com/rotternet"); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     static void DownloadDataCompleted(object sender, 
      DownloadDataCompletedEventArgs e) 
     { 



     } 


     public string SearchForText(string SearchParameter) 
     { 
      client.DownloadDataCompleted += DownloadDataCompleted; 
      client.DownloadDataAsync(new Uri(url)); 
      return SearchParameter; 
     } 

我要使用Web客戶端和downloaddataasync並在年底有一個字符串的網站源內容。

+1

爲什麼你同時擁有'webBrowser1'和'client'? – Oded 2012-08-09 20:03:02

+4

「我想起訴WebClient ..」:) :) – 2012-08-09 20:03:30

+0

網站和網頁有區別,在這種情況下非常重要。您正在下載單個頁面。它不會有任何鏈接的資源(圖像,CSS,JavaScript,幀),也不會下載任何鏈接的頁面。 – Sklivvz 2012-08-09 20:04:59

回答

4

使用WebRequest

WebRequest request = WebRequest.Create(url); 
request.Method = "GET"; 
WebResponse response = request.GetResponse(); 
Stream stream = response.GetResponseStream(); 
StreamReader reader = new StreamReader(stream); 
string content = reader.ReadToEnd(); 
reader.Close(); 
response.Close(); 

您可以輕鬆地從另一個線程中調用的代碼,或使用背景worer - 這將使你的UI響應而檢索數據。

6

無需異步,真正做到:

var result = new System.Net.WebClient().DownloadString(url) 

如果你不想阻止你的用戶界面,你可以把上面的一個BackgroundWorker。我建議這樣做而不是Async方法的原因是因爲它使用起來更簡單,並且因爲我懷疑你只是將這個字符串粘貼到UI的任何地方(BackgroundWorker會讓你的生活更輕鬆)。

4

如果您使用的是.NET 4.5,

public async void Downloader() 
{ 
    using (WebClient wc = new WebClient()) 
    { 
     string page = await wc.DownloadStringTaskAsync("http://chatroll.com/rotternet"); 
    } 
} 

爲3.5或4.0

public void Downloader() 
{ 
    using (WebClient wc = new WebClient()) 
    { 
     wc.DownloadStringCompleted += (s, e) => 
     { 
      string page = e.Result; 
     }; 
     wc.DownloadStringAsync(new Uri("http://chatroll.com/rotternet")); 
    } 
}