您可以使用 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!");
}
或者另一种方法可以使用将 WorkerReportsProgress 属性设置为 true 的 BackgroundWorker。然后您应该订阅事件 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;
}
在触发文件下载的按钮单击事件(或其他)中,您应该添加此代码以启动异步运行的后台工作器:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}