Best way to iterate folders and subfolders

2019-01-11 09:39发布

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?

5条回答
欢心
2楼-- · 2019-01-11 09:49

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-11 09:58

Note that you will need to perform validation checks.

string[] fileNames = Directory.GetFiles("c:\\", "*.*", SearchOption.AllDirectories);
int fileCount = fileNames.Count();
long fileSize = fileNames.Select(file => new FileInfo(file).Length).Sum(); // in bytes
查看更多
做个烂人
4楼-- · 2019-01-11 10:00

To iterate through all directories sub folders and files, no matter how much sub folder and files are.

string [] filenames;
 fname = Directory.GetFiles(jak, "*.*", SearchOption.AllDirectories).Select(x => Path.GetFileName(x)).ToArray();

then from array you can get what you want via a loop or as you want.

查看更多
We Are One
5楼-- · 2019-01-11 10:00

To iterate through files and folders you would normally use the DirectoryInfo and FileInfo types. The FileInfo type has a Length property that returns the file size in bytes.

I think you must write your own code to iterate through the files and calculate the total file size, but it should be a quite simple recursive function.

查看更多
成全新的幸福
6楼-- · 2019-01-11 10:07

Use Directory.GetFiles(). The bottom of that page includes an example that's fully recursive, I believe.

查看更多
登录 后发表回答