Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:
int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.
EDIT: If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?
You should use the Directory.GetFiles(path, searchPattern, SearchOption) overload of Directory.GetFiles().
Path specifies the path, searchPattern specifies your wildcards (e.g., *, *.format) and SearchOption provides the option to include subdirectories.
The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:
EDIT: Alternatively you can use Directory.EnumerateFiles method
I was looking for a more optimized version. Since I haven't found it, I decided to code it and share it here:
All the solutions using the GetFiles/GetDirectories are kind of slow since all those objects need to be created. Using the enumeration, it doesn't create any temporary objects (FileInfo/DirectoryInfo).
see Remarks http://msdn.microsoft.com/en-us/library/dd383571.aspx for more information
Using recursion your MagicFindFileCount would look like this:
Though Jon's solution might be the better one.
I have an app which generates counts of the directories and files in a parent directory. Some of the directories contain thousands of sub directories with thousands of files in each. To do this whilst maintaining a responsive ui I do the following ( sending the path to ADirectoryPathWasSelected method):
Someone has to do the iterating part.
AFAIK, there is no such method present in .NET already, so I guess that someone has to be you.
You can use this overload of GetFiles:
and this member of SearchOption:
GetFiles returns an array of string so you can just get the Length which is the number of files found.