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?
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.
System.IO.DirectoryInfo.EnumerateDirectories
System.IO.DirectoryInfo.EnumerateFiles
Directory.GetFiles
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.
The EnumerateFilesand GetFiles methods differ as follows:
EnumerateFiles
GetFiles
FileInfo
Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
2.1m questions
2.1m answers
60 comments
57.0k users