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 = "下载完成";
}
}
}
}
详尽 的注释。。。。