Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of files with a specific extension, in all subdirectories

Tags:

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?

like image 979
Espo Avatar asked Aug 26 '08 08:08

Espo


People also ask

How do I get a list of all file extensions?

If you add the -X option, ls will sort files by name within each extension category. For example, it will list files without extensions first (in alphanumeric order) followed by files with extensions like . 1, . bz2, .

How do I count the number of files in multiple folders?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.


1 Answers

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;

EDIT: Alternatively you can use Directory.EnumerateFiles method

return Directory.EnumerateFiles(@"c:\windows\system32", "*.dll", SearchOption.AllDirectories).Count();
like image 198
Jon Limjap Avatar answered Oct 18 '22 17:10

Jon Limjap