views:

1447

answers:

4

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?

A: 

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.

Lasse V. Karlsen
+11  A: 

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:

string[] files = directory.GetFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories);

return files.Length;
Jon Limjap
This has a massive performance issue with large number of files.
Aim Kai
@Aim - Can you (or anybody else) please quantify your statement? How slow is 'massive performance issue'? How many is 'large number of files'? Jon solution works for me but I'd like to know when/how it could become problematic.
David HAust
+1  A: 

You can use this overload of GetFiles:

Directory.GetFiles Method (String, String, SearchOption)

and this member of SearchOption:

AllDirectories - Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

GetFiles returns an array of string so you can just get the Length which is the number of files found.

John
A: 

Using recursion your MagicFindFileCount would look like this:

private int MagicFindFileCount( string strDirectory, string strFilter ) {
     int nFiles = Directory.GetFiles( strDirectory, strFilter ).Length;

     foreach( String dir in Directory.GetDirectories( strDirectory ) ) {
        nFiles += GetNumberOfFiles(dir, strFilter);
     }

     return nFiles;
  }

Though Jon's solution might be the better one.

Huppie