Unfortunately, you can't enumerate the contents of a directory in .NET 3.5 without using interop or obtaining all of the paths ahead of time. As mentioned, the disadvantage to using File.GetFiles()
is that it returns all the paths at once, which can consume more resources than required.
If you want to enumerate the contents of the directory and increment a counter as you enumerate, you may try one of the following options.
- Using .NET interop, call FindFirstFile and FindNextFile with the . pattern, incrementing a counter for each successful invocation.
- Utilize features of .NET 4.0 which allow you to obtain an
IEnumerable<T>
for enumerating the contents of a directory.
Whenever interop is used, you should be concerned about the performance of making native WinAPI calls from managed code. Consider utilizing a profiler to determine if the performance penalty is acceptable.