views:

299

answers:

2

Is there a way (on windows using Delphi 2010) to get the number of files in a dirctory without actually traversing all files?

I want to implement a progress bar during some file system indexing operation. For that reason I need to know how many files are in the directory.

What is the fastest way to get the number of files in a directory?

+6  A: 

I think the fastest way is to use the TDirectory.GetFiles method located in IOutils.pas. As the number of (visible) files in a directory may be different for each user, there is only a tiny chance that there is just a number to retrieve somehow.

The FindFirst/FindNext approach (which is wrapped in the above method) doesn't actually traverse files, it only traverses entries in a table, so it might be faster than expected.

Uwe Raabe
+7  A: 

If you are running on Windows 7 or Server 2008 R2, I recommend extracting the FindFirst and FindMatchingFile functions from SysUtils and hacking the former to use FindFirstFileEx instead of FindFirstFile. Then you can set the additional flags parameter to 2 (defined in MSDN as FIND_FIRST_EX_LARGE_FETCH) with this setting conditioned on (Win32majorversion = 6) and (Win32minorversion >= 1), for the time being.

This setting produces a very significant speed increase for FindFirst/FindNext loops on these OS. Look for FindFirstFileEx on MSDN for more details, as the latest documentation is not in the Microsoft documentation retrieved by Delphi help.

TDirectory.GetFiles eventually seems to call FindFirst, so will not buy you much advantage other than simplifying your own code.

frogb
+1 interesting!
Smasher