Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reporting Progress on Directory.GetFiles

Tags:

c#

.net-4.0

Is there a quick way to load in the fully qualified path to every file (that you have read access to) starting with a supplied root directory into say a string[]?

I saw System.IO.Directory.GetFiles, but you have to supply a filter before you're allowed to input the SearchOption.AllDirectories, so I tried:

string[] directoryList = Directory.GetFiles(RootPath, "*.*",
                                            SearchOption.AllDirectories);

Where RootPath is my valid, rooted directory. This seemed to work OK, except that it hung my windows form app up for a very long time when pointing it to a large directory/file structure of 29GB and a few hundred thousand files.

So I thought about threading it via a BackgroundWorker so that my GUI didn't appear locked up, but I'm not sure how I'd report progress for something like this for a ProgressBar since it's just one statement that's doing the loading and I've no information on the total number of files upfront, or the number it has processed already etc.

like image 217
user17753 Avatar asked Aug 16 '12 20:08

user17753


1 Answers

With Directory.GetFiles, you'll always block until all of the results are completely processed, which can take a long time on a large directory structure.

You can use Directory.EnumerateFiles instead of Directory.GetFiles. This returns the results as an IEnumerable<string> instead of an array, so you can start processing (or reporting progress) the results immediately.

Otherwise, the best option is to use Directory.GetFiles, but not SearchOption.AllDirectories. You can then use Directory.GetDirectories to handle the recursion yourself, and parse the results in stages.

like image 115
Reed Copsey Avatar answered Sep 22 '22 09:09

Reed Copsey