7

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#?

2
  • Short answer: No there isn't. Even if you get some API to do that, It will enumerate internally. Commented Aug 11, 2014 at 9:28
  • 2
    but if the directory contains a lot of files (more than 50000) it takes too time. this is not possible Commented Aug 11, 2014 at 9:33

4 Answers 4

9

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(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

Am I doing something odd or does this not search the baseDir for files also?
Ah it's because it is enumerating the directories, but doesn't search itself.
4

I actually never tried a faster way but its a good question.. By searching I've found this

http://www.codeproject.com/Articles/38959/A-Faster-Directory-Enumerator

The Benchmark comparison looks quite nice..

MayBe this helps..

1 Comment

I've used the FastDirectoryEnumerator class a number of times, and it's ridiculously faster than all of the built-in methods for enumeration. It achieves this by avoiding large pre-allocations, caching intermediate results, and running tasks in parallel. Highly recommended!
-2

hi maybe this help it return string[]

String[] files = Directory.GetFileSystemEntries("path"); 

Comments

-2

I think you have to use Directory.GetFiles() or the DirectoryInfo class.

The Advantage is, that you can use an overload of GetFIles to search for files inside subdirectories e.g.

int allfilesCount = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length; 

MSDN DirectoryInfo

Mybe you could try

Directory.EnumerateFiles().Count() 

if it is faster.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.