Prescient Prescient - 1 year ago 67
C# Question

Get first file in folder with millions of files

I have to do some house cleaning on a folder with millions of files. Ultimately I would like to grab the files and then see if they exist in a database or not. But I need to first grab the files without the program choking.

I tried going the route of using

var file = Directory.GetFiles(uri, "*.*").FirstOrDefault();

however this takes forever to run. Because of the number of files.

Is there a better way to grab the files that won't take so long?

Answer Source

Yes, Directory.EnumerateFiles is what you're looking for. This will lazy load your files, so issuing a FirstOrDefault() will not wait for all files to be read.

From the docs:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

Aside from this - having a folder with millions of files is just a bad idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download