Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count of files from directory without enumerating files in c#

Tags:

c#

file

directory

I am using Directory.EnumerateFiles() and Directory.GetFiles() to get the count of files in a specific directory in c#. The problem is that theses methods are slow because they enumerate files to get there count.

How to get the count of files in Directory without enumerating files in c#?

like image 714
Mohamed Al-Hosary Avatar asked Feb 12 '23 07:02

Mohamed Al-Hosary


1 Answers

You have to enumerate through the folder in order to get all the files.

However, you can still do something to improve the performance. I suggest you have a look at those benchmark tests (Get1 method):

https://stackoverflow.com/a/17756559/3876750

It seems like the following method provides the best performance, according to the benchmark test:

private static int Get1(string myBaseDirectory)
{
    DirectoryInfo dirInfo = new DirectoryInfo(myBaseDirectory);
    return dirInfo.EnumerateDirectories()
           .AsParallel()
           .SelectMany(di => di.EnumerateFiles("*.*", SearchOption.AllDirectories))
           .Count();
}
like image 104
Andreas Avatar answered Feb 15 '23 10:02

Andreas