WebClient下載文件展示進度條

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace WebClientDownFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnDown_Click(object sender, EventArgs e)
        {
            string url = "https://fishc.com.cn/ucenter/data/avatar/000/00/00/09_avatar_middle.jpg";//需要下載的文件
            string fileExt = Path.GetExtension(url);//文件格式
            string path = Application.StartupPath + $"\\Files\\{DateTime.Now.ToString("yyyyMMddHHmmss")}{fileExt}";//保存到本地的目錄
            DownFile(url, path);//下載文件
        }
        private void DownFile(string url, string fileName)
        {
            try
            {
                WebClient client = new WebClient();//實例化webclient
                client.DownloadFileCompleted += Client_DownloadFileCompleted;//下載完文件觸發此事件
                client.DownloadProgressChanged += Client_DownloadProgressChanged;//下載進度變化觸發事件
                client.DownloadFileAsync(new Uri(url), fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //下載進度變化觸發事件
        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.progressBar1.Minimum = 0;//進度條最小值
            this.progressBar1.Maximum = (int)e.TotalBytesToReceive;//下載文件的總大小
            this.progressBar1.Value = (int)e.BytesReceived;//已經下載的大小
            this.lblPercent.Text = e.ProgressPercentage + "%";//更新界面展示
        }
        //下載完文件觸發此事件
        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.UserState == null)
            {
                this.lblMessage.Text = "下載完成";
            }
        }
    }
}

詳盡 的註釋。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章