开发者

Download multiple files from an array C#

开发者 https://www.devze.com 2022-12-24 18:47 出处:网络
I have an array of file names which I want to download. The array is currently contained in a string[] and it is working inside of a BackgroundWorker.

I have an array of file names which I want to download.

The array is currently contained in a string[] and it is working inside of a BackgroundWorker.

What I want to do is use that array to download files and output the result into a progress bar which will tell me how long I 开发者_JAVA技巧have left for completion.

Is there a way I can do this.

Thanks.


Use WebClient to download files, there's a method called "DownloadFile".

Pseudo code

foreach(var url in listOfStringURLS)
{
    WebClient.DownloadFile(url, ".");
    updateProgressBar();
}

That's the Easy part! Now, you need to know that when you are using a BackgroundWorker, you are no longer on the GUI-thread, which means that you Cannot update the ProgressBar without using a Delegate! Check this out: "Progress Bar Delegate".

For .NET 4.0

You might want to parallelize the downloads! You can do this easily with .NET 4.0 by looking in to Tasks, check this blog about Paralell Programming. Otherwise you will, as another poster said have all IO on 1 thread, which may be not so optimized.


If you handle this from the backgroundworker you have 1 thread doing all your I/O. That is OK, but maybe not the fastest.

The backgroundworker has an ProgressChanged event, a ReportProgress() method and a Supportsprogress property.

  1. Set the property to true
  2. Call ReportProgress(percentage) fro DoWork
  3. handle the ProgressChanged event to set the progressbar.


Simply use: ReportProgress((100 * currentItem) / list.Count) and let the BackgroundWorker.ProgressChanged event handler update the progress bar (you might have to check if invoke is required and use invoke to update).

The ProgressChanged event handler can then calculate the remaining time.

Ofc this is not precise if the size of the elements varies much.

You might want to look at http://msdn.microsoft.com/en-us/library/system.net.webclient.downloadfileasync.aspx which removes the need for a seperate background worker.

0

精彩评论

暂无评论...
验证码 换一张
取 消