在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
以前在百度写的文档,转移到此处
软件截图:
代码下载: http://twzy.ys168.com/ 在代码下载文件夹中
//代码: using System; using System.ComponentModel; using System.Net; using System.Threading; using System.Windows.Forms; namespace DownFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string netPath = "http://wlkt.zufe.edu.cn/Skyclass/C91/Courseware/Bbs/080717071122.mp3";//需要下载的文件 string filePath = "D:\\just one last dance.mp3";//文件保存的路径 delegate void delDownFileHandler(int totalNum, int num, int proc);//用于指示文件信息(文件大小,当前下载的数量,当前下载的百分比) delegate void delComDownFileHandler(bool isCompleted);//文件下载完成之后 WebClient wc = new WebClient(); private void button1_Click(object sender, EventArgs e) { wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted); progressBar1.Value = 0; label1.Text = ""; button2.Enabled = true; button1.Enabled = false; //使用线程启动 Thread td = new Thread(new ThreadStart(loadFile)); td.IsBackground = true; td.Start(); } //线程启动 private void loadFile() { if (wc.IsBusy) { wc.CancelAsync(); } wc.DownloadFileAsync(new Uri(netPath), filePath); } //更新过程中触发的事件(在线程中不能直接操纵控件,因此用委托执行) void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { this.Invoke(new delDownFileHandler(processShow), new object[] { (int)e.TotalBytesToReceive, (int)e.BytesReceived, e.ProgressPercentage }); } //委托执行 (进度条和字符标识) private void processShow(int totalNum, int num, int proc) { progressBar1.Maximum = totalNum; progressBar1.Value = num; label1.Text = "正在下载:" + (num / (1024)).ToString() + "KB/" + (totalNum / 1024).ToString() + "KB " + proc.ToString() + "%"; } //完成更新之后触发的事件 void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) this.Invoke(new delComDownFileHandler(comDownFile), new object[] { false }); else this.Invoke(new delComDownFileHandler(comDownFile), new object[] { true }); } private void comDownFile(bool isCompleted) { if (isCompleted) label1.Text = "下载完成"; else label1.Text = "下载取消"; progressBar1.Value = 0; button1.Enabled = true; button2.Enabled = false; } //点击取消后 private void button2_Click(object sender, EventArgs e) { wc.CancelAsync(); wc.Dispose(); } } } 代码中的文件路径已经失效,请自行修改
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论