2012-08-09 44 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")); 
    } 
}