3

私はこれを試しましたが、Webサイトのソースコンテンツが文字列にダウンロードされるようにしたいと思います。

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;
        }

WebClientとdownloaddataasyncを使用して、最終的にWebサイトのソースコンテンツを文字列にしたいと思います。

4

3 に答える 3

7

非同期の必要はありません、本当に:

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

UIをブロックしたくない場合は、上記をBackgroundWorkerに入れることができます。Asyncメソッドではなくこれを提案する理由は、使用が劇的に簡単であり、とにかくこの文字列をUIに貼り付けるだけであると思われるためです(BackgroundWorkerを使用すると作業が楽になります)。

于 2012-08-09T20:02:44.607 に答える
6

.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"));
    }
}
于 2012-08-09T20:16:25.303 に答える
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();

別のスレッド内からコードを簡単に呼び出すことも、バックグラウンドワーラーを使用することもできます。これにより、データの取得中にUIが応答しやすくなります。

于 2012-08-09T20:14:21.823 に答える