我想在我的Windows窗體應用程序中使用進度條。該應用程序將用於將文件從目錄下載到另一個目錄。如何使用進度條進行下載
但應用程序看起來無所事事,當用戶點擊下載按鈕。所以我想用進度條向用戶展示下載過程。
我做搜索的進度條,但我無法找到的「如何使用進度條下載的過程」的答案。
,我會很高興,如果有人向我解釋如何使用進度條下載的過程。
我想在我的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;
}
在按鈕單擊事件(或其他)觸發文件的下載,你應該添加此代碼啓動後臺工作異步運行:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
的WebClient
有DownloadProgressChanged
- 活動。把它掛到進度條上,你很好走。 MSDN
備註:您需要使用DownloadDataAsync
,DownloadFileAsync
或OpenReadAsync
爲DownloadProgressChanged
- 活動火。
首先,你知道(a)總文件大小,和(b)到目前爲止下載的數量? –