winform 下载

Posted on 2014-09-26 17:30  月下小王子  阅读(1671)  评论(0编辑  收藏  举报

方法一:

WebClient webClint = new WebClient();

webClint.DownloadFile(下载文件的路径,下载到本地的地址);

方法二:异步

WebClient webClint;
        float maxSpeed = 0;
        float currentSpeed = 0;
        float lastSpeed = 0;
        long lastReceive = 0;
        long reeciveSpan;
        TimeSpan span;
        DateTime start;
        DateTime lastTime;
        TimeSpan useTime;
        protected void Button1_Click(object sender, EventArgs e)
        {

 webClint.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClint_DownloadProgressChanged);
  webClint.DownloadFileAsync(new Uri下载文件的路径, 下载到本地的地址);

}

void webClint_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            span = DateTime.Now - lastTime;
            lastTime = DateTime.Now;
            useTime = lastTime - start;
            reeciveSpan = e.BytesReceived - lastReceive;
            currentSpeed = reeciveSpan * 1000 / (span.Milliseconds + 1) / 1024;
            maxSpeed = currentSpeed > maxSpeed ? currentSpeed : maxSpeed;
            lastSpeed = currentSpeed;
            lastReceive = e.BytesReceived;
           // progressBar1.Value = e.ProgressPercentage;
            this.Label1.Text = "已下载: " + e.BytesReceived / 1024 + "KB\n" +
                "总大小: " + e.TotalBytesToReceive / 1024 + "KB\n" +
                "百分比: " + e.ProgressPercentage + "%\n" +
                "当前速度: " + currentSpeed.ToString("F2") + "KB/s\n" +
                "大速度: " + maxSpeed.ToString("F2") + "KB/s\n" +
                "用时: " + (useTime.Minutes * 60 + useTime.Seconds) + "s";

            if (e.BytesReceived == e.TotalBytesToReceive)
            {
                webClint.DownloadProgressChanged -= webClint_DownloadProgressChanged;
                webClint.Dispose();
                Response.Write("任务完成!");
                webClint.Dispose();
                //if (MessageBox.Show("是否关闭当前程序而立即安装?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                //{
                //    xiazai();
                //}
            }

        }