Best way to iterate folders and subfolders

Rod picture Rod · Mar 3, 2011 · Viewed 82.4k times · Source

What's the best way to iterate folders and subfolders to get file size, total number of files, and total size of folder in each folder starting at a specified location?

Answer

Chris Dunaway picture Chris Dunaway · Mar 3, 2011

If you're using .NET 4, you may wish to use the System.IO.DirectoryInfo.EnumerateDirectories and System.IO.DirectoryInfo.EnumerateFiles methods. If you use the Directory.GetFiles method as other posts have recommended, the method call will not return until it has retrieved ALL the entries. This could take a long time if you are using recursion.

From the documentation:

The EnumerateFilesand GetFiles methods differ as follows:

  • When you use EnumerateFiles, you can start enumerating the collection of FileInfo objects before the whole collection is returned.
  • When you use GetFiles, you must wait for the whole array of FileInfo objects to be returned before you can access the array.

Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.