首页 > 代码库 > winform 下载

winform 下载

方法一:

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 = http://www.mamicode.com/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();
                //}
            }

        }

winform 下载