如何使用进度条下载过程
本文关键字:下载 过程 何使用 | 更新日期: 2023-09-27 17:50:37
我想在我的windows窗体应用程序中使用进度条。该应用程序将用于将文件从一个目录下载到另一个目录。
但是当用户点击下载按钮时,应用程序似乎什么都不做。我想用进度条向用户展示下载的过程。
我确实搜索了进度条,但我找不到"如何使用进度条进行下载过程"的答案。
如果有人告诉我如何使用进度条下载过程,我将非常高兴。
你可以使用DownloadFileAsync下载文件而不阻塞主线程,并设置一个事件处理程序来显示进度条:
private void button1_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
string sourceFile = @"''server'test.txt";
string destFile = @"''server2'test2.txt";
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(sourceFile), destFile);
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("The download is completed!");
}
或者另一种方法可以使用BackgroundWorker,并将属性WorkerReportsProgress设置为true。然后你应该订阅事件DoWork和ProgressChanged:在DoWork方法中,你把代码下载或传输文件在一个单独的线程上,并计算工作的进度。在ProgressChanged方法中,只需更新进度条的值。在这种情况下,您的代码看起来像这样:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// the path of the source file
string sourceFile = @"''shared'test.txt";
// the path to write the file to
string destFile = @"''shared2'test2.txt";
FileInfo info = new FileInfo(sourceFile);
// gets the size of the file in bytes
Int64 size = info.Length;
// keeps track of the total bytes downloaded so you can update the progress bar
Int64 runningByteTotal = 0;
using (FileStream reader = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
{
using (Stream writer = new FileStream(destFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
int iByteSize = 0;
byte[] byteBuffer = new byte[size];
while ((iByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
// write the bytes to the file
writer.Write(byteBuffer, 0, iByteSize);
runningByteTotal += iByteSize;
// calculate the progress
double index = (double)(runningByteTotal);
double total = (double)byteBuffer.Length;
double progressPercentage = (index / total);
int iProgressPercentage = (int)(progressPercentage * 100);
// update the progress bar
backgroundWorker1.ReportProgress(iProgressPercentage);
}
// clean up the file stream
writer.Close();
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
在触发文件下载的按钮点击事件(或其他)中,您应该添加以下代码来启动后台worker异步运行:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
WebClient
存在DownloadProgressChanged
-Event。把它连接到进度条上,你就可以开始了。MSDN
备注:DownloadProgressChanged
-Event需要使用DownloadDataAsync
, DownloadFileAsync
或OpenReadAsync
触发