webclient下载文件 带进度条

private void button1_Click(object sender, EventArgs e)
  {
      doDownload(textBox1.Text.Trim());
  }
 
  private DateTime StartTime;
  private void doDownload(string url,string fileName="")
  {
 
      label1.Text = "正在下载:" + url;//label框提示下载文件
      if (fileName.Length==0)
      {
          fileName = url.Substring(url.LastIndexOf("/") + 1);
      }
      StartTime = DateTime.Now;
      progressBar1.Value = 0;//初始化单个文件下载条
      WebClient ws = new WebClient();
      ws.DownloadProgressChanged += OnDownloadProgressChanged;
      //绑定下载事件,以便于显示当前进度
      ws.DownloadFileCompleted += OnDownloadFileCompleted;
      //绑定下载完成事件,以便于计算总进度
      ws.DownloadFileAsync(new Uri(url), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName));
      //调用DownloadFileAsync方法下载文件
      //DownloadFileAsync有2个重载,另一个我没搞明白最后一个参数该传什么,有哪位朋友知道的,请留言告诉我谢谢
      //upapp是我一个实体类,UpdateURL存放了下载的地址(值为http://www.harde.com.cn/SoftUpdate/)
      //Path.Combine()是一个用来连接地址的方法,我将在另一日志中详细对其介绍
  }
  /// 下载进程变更事件
  private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  {
      //在网上看到有朋友这么来控制进度条,我觉得麻烦,毕竟有省事的为什么我要麻烦一番……
      //this.SetProcessBar(e.ProgressPercentage, (int)((nDownloadedTotal + e.BytesReceived) * 100 / total));
      progressBar1.Value = e.ProgressPercentage;
      var s = (DateTime.Now - StartTime).TotalSeconds;
      var sd = ReadableFilesize(e.BytesReceived/s);
      label1.Text = "下载速度"+sd+"/秒"+",已下载" + ReadableFilesize(e.BytesReceived) + "/总计" + ReadableFilesize(e.TotalBytesToReceive) ;//一个label框,用来显示当前下载的数据
  }
  /// 下载进程变更事件
  private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  {
      MessageBox.Show("complied!");
  }
  private string ReadableFilesize(double size)
  {
      String[] units = { "B", "KB", "MB", "GB", "TB", "PB" };
      double mod = 1024.0;
      int i = 0;
      while (size >= mod)
      {
          size /= mod;
          i++;}
      return Math.Round(size) + units[i];
  }

  

posted @   simadi  阅读(1151)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2014-07-06 Visual Studio 2013中c#语言规范5.0
点击右上角即可分享
微信分享提示