« In retrospect, maybe we were wrong
Trees in relational databases »


Code Snippet of the Day: Recursive File Finder

.NET doesn't have a recursive file finding class, so I've used this helper a couple of times:

    ///

    /// Finds a list of files that match the specified critiria

    ///

    public class FileFinder

    {

        private Dictionary<FileInfo,int> files;

 

        ///

        /// Returns all files that match MatchType that are children of StartDir

        ///

        ///

        ///

        ///

        public List<FileInfo> Find(string startDir, string matchType)

        {

            files = new Dictionary<FileInfo, int>();

            findFiles(startDir, matchType);

 

            return files.Keys.ToList();

        }

 

        private void findFiles(string startDir, string matchType)

        {

            DirectoryInfo d = new DirectoryInfo(startDir);

            foreach (FileInfo f in d.GetFiles(matchType))

            {

                if (!files.ContainsKey(f))

                {

                    files.Add(f, 0);

                }

            }

 

            if (d.GetDirectories().Length > 0)

            {

                foreach (DirectoryInfo subD in d.GetDirectories())

                {

                    findFiles(subD.FullName, matchType);

                }

            }

        }

 

    }


To use:

FileFinder fFinder = new FileFinder();

List<FileInfo> files = fFinder.Find("C:\\","*.dll");



Posted by Jonathan Holland on 5/28/2009.

Tags: .NET

Comments:

Have you tried the Stack<> method from http://dotnetperls.com/Content/Recursively-Find-Files.aspx ? I can do my c:\windows folder (13,300 dll files) in 5767 ms. The recursive way takes 6854ms.

public List Find(string startDir, string matchType) { DirectoryInfo dirStart = new DirectoryInfo(startDir); List result = new List(); Stack stack = new Stack(); stack.Push(dirStart); while (stack.Count > 0) { DirectoryInfo dir = stack.Pop(); try { result.AddRange(dir.GetFiles(matchType)); DirectoryInfo[] subDirs = dir.GetDirectories(); foreach (DirectoryInfo dn in subDirs) { stack.Push(dn); } } catch{} } return result; }

Gravatar Posted by Vince Zalamea on 6/7/2009.

I tested this vs using Stack<> and Stack<> was faster. http://www.thevincefiles.net/2009/06/07/finding-files-recursion-vs-stackfight

Gravatar Posted by Vince Zalamea on 6/7/2009.

@Vince

Recursion uses a stack, it just reuses the callstack. The generic stack technique will be slightly faster, but has a much larger memory footprint.

Gravatar Posted by Jonathan Holland on 6/7/2009.

Comments are closed on this post.