如何将网站内容下载到字符串?

use*_*479 3 c#

我试过这个,我希望网站的源内容将下载到一个字符串:

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;
        }
Run Code Online (Sandbox Code Playgroud)

我想使用WebClient并下载数据同步,最后将网站源内容放在一个字符串中.

Chr*_*ain 7

真的不需要异步:

var result = new System.Net.WebClient().DownloadString(url)
Run Code Online (Sandbox Code Playgroud)

如果您不想阻止UI,可以将上述内容放在BackgroundWorker中.我建议使用它而不是Async方法的原因是因为它使用起来非常简单,并且因为我怀疑你只是将这个字符串粘贴到UI的某个地方(BackgroundWorker将使你的生活更轻松).


Mac*_*ska 5

使用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();
Run Code Online (Sandbox Code Playgroud)

您可以轻松地从另一个线程中调用代码,或使用背景文件 - 这将使您的UI在检索数据时响应.


L.B*_*L.B 5

如果您使用的是.Net 4.5,

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

适用于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"));
    }
}
Run Code Online (Sandbox Code Playgroud)