<p>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:</p>

<pre><code>int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll");
</code></pre>

<p>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.</p>

<p><strong>EDIT:</strong> If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?</p>

[{'answer_id': 27574, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': '<p>Someone has to do the iterating part.</p>\n\n<p>AFAIK, there is no such method present in .NET already, so I guess that someone has to be you.</p>\n'}, {'answer_id': 27584, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 6, 'selected': True, 'text': '<p>You should use the <a href="http://msdn.microsoft.com/en-us/library/ms143316.aspx" rel="noreferrer">Directory.GetFiles(path, searchPattern, SearchOption)</a> overload of Directory.GetFiles().</p>\n\n<p>Path specifies the path, searchPattern specifies your wildcards (e.g., *, *.format) and SearchOption provides the option to include subdirectories.</p>\n\n<p>The Length property of the return array of this search will provide the proper file count for your particular search pattern and option:</p>\n\n<pre><code>string[] files = directory.GetFiles(@"c:\\windows\\system32", "*.dll", SearchOption.AllDirectories);\n\nreturn files.Length;\n</code></pre>\n\n<p><strong>EDIT:</strong> Alternatively you can use <a href="https://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles(v=vs.110).aspx" rel="noreferrer">Directory.EnumerateFiles method</a></p>\n\n<pre><code>return Directory.EnumerateFiles(@"c:\\windows\\system32", "*.dll", SearchOption.AllDirectories).Count();\n</code></pre>\n'}, {'answer_id': 27585, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 3, 'selected': False, 'text': '<p>You can use this overload of GetFiles:</p>\n<blockquote>\n<p><a href="http://msdn.microsoft.com/en-us/library/ms143316.aspx" rel="noreferrer"> Directory.GetFiles Method (String,\nString, SearchOption</a>)</p>\n</blockquote>\n<p>and this member of SearchOption:</p>\n<blockquote>\n<p><strong>AllDirectories</strong> - Includes the current\ndirectory and all the subdirectories\nin a search operation. This option\nincludes reparse points like mounted\ndrives and symbolic links in the\nsearch.</p>\n</blockquote>\n<p>GetFiles returns an array of string so you can just get the Length which is the number of files found.</p>\n'}, {'answer_id': 27592, 'author': 'Huppie', 'author_id': 1830, 'author_profile': 'https://Stackoverflow.com/users/1830', 'pm_score': 1, 'selected': False, 'text': '<p>Using recursion your MagicFindFileCount would look like this:</p>\n\n<pre><code>private int MagicFindFileCount( string strDirectory, string strFilter ) {\n     int nFiles = Directory.GetFiles( strDirectory, strFilter ).Length;\n\n     foreach( String dir in Directory.GetDirectories( strDirectory ) ) {\n        nFiles += GetNumberOfFiles(dir, strFilter);\n     }\n\n     return nFiles;\n  }\n</code></pre>\n\n<p>Though <a href="https://stackoverflow.com/questions/27570/find-number-of-files-in-all-subdirectories#27584">Jon\'s solution</a> might be the better one.</p>\n'}, {'answer_id': 5410210, 'author': 'Sauleil', 'author_id': 331752, 'author_profile': 'https://Stackoverflow.com/users/331752', 'pm_score': 3, 'selected': False, 'text': '<p>I was looking for a more optimized version. Since I haven\'t found it, I decided to code it and share it here:</p>\n\n<pre><code>    public static int GetFileCount(string path, string searchPattern, SearchOption searchOption)\n    {\n        var fileCount = 0;\n        var fileIter = Directory.EnumerateFiles(path, searchPattern, searchOption);\n        foreach (var file in fileIter)\n            fileCount++;\n        return fileCount;\n    }\n</code></pre>\n\n<p>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).</p>\n\n<p>see Remarks <a href="http://msdn.microsoft.com/en-us/library/dd383571.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd383571.aspx</a> for more information</p>\n'}, {'answer_id': 7430990, 'author': 'Dean', 'author_id': 257810, 'author_profile': 'https://Stackoverflow.com/users/257810', 'pm_score': 3, 'selected': False, 'text': '<p>The slickest method woud be to use linq:</p>\n\n<pre><code>var fileCount = (from file in Directory.EnumerateFiles(@"H:\\iPod_Control\\Music", "*.mp3", SearchOption.AllDirectories)\n                    select file).Count();\n</code></pre>\n'}, {'answer_id': 10193988, 'author': 'DraxReaper', 'author_id': 1315396, 'author_profile': 'https://Stackoverflow.com/users/1315396', 'pm_score': 1, 'selected': False, 'text': '<p>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 <em>ADirectoryPathWasSelected</em> method):</p>\n\n<pre><code>public class DirectoryFileCounter\n{\n    int mDirectoriesToRead = 0;\n\n    // Pass this method the parent directory path\n    public void ADirectoryPathWasSelected(string path)\n    {\n        // create a task to do this in the background for responsive ui\n        // state is the path\n        Task.Factory.StartNew((state) =&gt;\n        {\n            try\n            {\n                // Get the first layer of sub directories\n                this.AddCountFilesAndFolders(state.ToString())\n\n\n             }\n             catch // Add Handlers for exceptions\n             {}\n        }, path));\n    }\n\n    // This method is called recursively\n    private void AddCountFilesAndFolders(string path)\n    {\n        try\n        {\n            // Only doing the top directory to prevent an exception from stopping the entire recursion\n            var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);\n\n            // calling class is tracking the count of directories\n            this.mDirectoriesToRead += directories.Count();\n\n            // get the child directories\n            // this uses an extension method to the IEnumerable&lt;V&gt; interface,\n           // which will run a function on an object. In this case \'d\' is the \n           // collection of directories\n            directories.ActionOnEnumerable(d =&gt; AddCountFilesAndFolders(d));\n        }\n        catch // Add Handlers for exceptions\n        {\n        }\n        try\n        {\n            // count the files in the directory\n            this.mFilesToRead += Directory.EnumerateFiles(path).Count();\n        }\n        catch// Add Handlers for exceptions\n        { }\n    }\n}\n// Extension class\npublic static class Extensions\n{ \n    // this runs the supplied method on each object in the supplied enumerable\n    public static void ActionOnEnumerable&lt;V&gt;(this IEnumerable&lt;V&gt; nodes,Action&lt;V&gt; doit)\n    {\n\n        foreach (var node in nodes)\n        {   \n            doit(node);\n        }\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/27570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2257/']