码迷,mamicode.com
首页 > Web开发 > 详细

WebClient的使用

时间:2017-05-09 20:36:16      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:open   wait   save   false   name   硬盘   dispose   button   art   

1、下载网页源码:

   private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url);

            WebClient wc = new WebClient();
           wc.DownloadDataAsync(new Uri(url));
           wc.DownloadDataCompleted += wc_DownloadDataCompleted;
        }

        void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error == null && e.Cancelled == false)
                textBox2.Text = Encoding.UTF8.GetString(e.Result);
            else
                MessageBox.Show(e.Error.Message);
        }

 2、直接下载文件,比较简单,但下载比较伤硬盘:

        private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url);

            WebClient wc = new WebClient();
            wc.DownloadFileCompleted += wc_DownloadFileCompleted;
            wc.DownloadFileAsync(new Uri(url), toUrl);
        }

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show("下载完成");
        }

3、利用缓存下载文件,可以更好的保护硬盘

private void button2_Click(object sender, EventArgs e)
        {
            WebClient wc = new WebClient();
            wc.OpenReadAsync(new Uri(textBox1.Text));
            wc.OpenReadCompleted += wc_OpenReadCompleted;
        }
        async void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                await SaveFile(e.Result, Application.StartupPath + "\\" + Path.GetFileName(textBox1.Text));
                MessageBox.Show("下载完成");
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }
        Task SaveFile(Stream stream, string savepath)
        {
            return Task.Run(() =>
              {
                  var read = stream;
                  byte[] buf = new byte[8192];
                  int res = 0;
                  FileStream fs = File.Open(savepath, FileMode.OpenOrCreate);
                  using (fs)
                  {
                      while ((res = read.Read(buf, 0, buf.Length)) > 0)
                      {
                          fs.Write(buf, 0, res);
                          fs.Flush();
                      }
                  }
                  read.Close();
                  read.Dispose();
              });
        }
 

4、上传文件

WebClient的使用

标签:open   wait   save   false   name   硬盘   dispose   button   art   

原文地址:http://www.cnblogs.com/lunawzh/p/6832282.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!