C# 用带百分比的进度条显示下载文件进度,网上看到的教程都很麻烦,自己随便做了一个。用博客写编程果然很费劲,顺便做了个 Youtube Video。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace downloadDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
WebClient client;
private void button1_Click(object sender, EventArgs e)
{
string url = textBox1.Text;
if (!string.IsNullOrEmpty(url))
{
Uri uri = new Uri(url);
string fileName = System.IO.Path.GetFileName(uri.AbsolutePath);
client.DownloadFileAsync(uri, Application.StartupPath + "/" + fileName);
}
}
private void Form1_Load(object sender, EventArgs e)
{
client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed");
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Minimum = 0;
double receive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = receive / total * 100;
lblStatus.Text = string.Format("{0:0.##}", percentage) + "%";
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
}
}
另外如果想自己用KB大小显示的话也可以直接修改
lblStatus.Text = string.Format("{0:0.##}", percentage) + "%";
为
lblStatus.Text = receive.ToString() + "/" + total.ToString();
自己直接转换下KB单位就可以了。