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

前端 未结 7 1760
执念已碎
执念已碎 2020-12-03 07:16

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 somet

相关标签:
7条回答
  • 2020-12-03 08:22

    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):

    public class DirectoryFileCounter
    {
        int mDirectoriesToRead = 0;
    
        // Pass this method the parent directory path
        public void ADirectoryPathWasSelected(string path)
        {
            // create a task to do this in the background for responsive ui
            // state is the path
            Task.Factory.StartNew((state) =>
            {
                try
                {
                    // Get the first layer of sub directories
                    this.AddCountFilesAndFolders(state.ToString())
    
    
                 }
                 catch // Add Handlers for exceptions
                 {}
            }, path));
        }
    
        // This method is called recursively
        private void AddCountFilesAndFolders(string path)
        {
            try
            {
                // Only doing the top directory to prevent an exception from stopping the entire recursion
                var directories = Directory.EnumerateDirectories(path, "*.*", SearchOption.TopDirectoryOnly);
    
                // calling class is tracking the count of directories
                this.mDirectoriesToRead += directories.Count();
    
                // get the child directories
                // this uses an extension method to the IEnumerable<V> interface,
               // which will run a function on an object. In this case 'd' is the 
               // collection of directories
                directories.ActionOnEnumerable(d => AddCountFilesAndFolders(d));
            }
            catch // Add Handlers for exceptions
            {
            }
            try
            {
                // count the files in the directory
                this.mFilesToRead += Directory.EnumerateFiles(path).Count();
            }
            catch// Add Handlers for exceptions
            { }
        }
    }
    // Extension class
    public static class Extensions
    { 
        // this runs the supplied method on each object in the supplied enumerable
        public static void ActionOnEnumerable<V>(this IEnumerable<V> nodes,Action<V> doit)
        {
    
            foreach (var node in nodes)
            {   
                doit(node);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题