Using just .NET's standard library, the fastest option is
int count = Directory.EnumerateFiles(...).Count();
This will be faster than say getting the files themselves through a foreach loop since we are not retrieving and thus constructing the file info object that is being iterated. Though, this is not the end of the story.
There's other posts asking about listing directories and subdirectories fast, and through research I came up with a faster implementation, in this repository (NuGet package soon).
Example for 300k files spread within 300 subdirectories:
| Method | Mean | Ratio | Allocated | Alloc Ratio |
|---|---|---|---|---|
| GetFileCount | 111.1 ms | 0.95 | 99.25 KB | 0.004 |
| Directory_EnumerateFiles | 116.6 ms | 1.00 | 25741.13 KB | 1.000 |
The allocations are avoided by reusing the same struct when invoking the Windows APIs, and only allocating strings that are required for calculating the path of the subdirectories to iterate next.
And for the above example, it seems that we have hit the API/IO bottleneck, so it can probably be barely improved. The major impact is the allocation reduction though, which is huge for much denser and more packed directories.