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?
问题:
回答1:
Use Directory.GetFiles(). The bottom of that page includes an example that's fully recursive, I believe.
回答2:
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
EnumerateFiles
andGetFiles
methods differ as follows:
- When you use
EnumerateFiles
, you can start enumerating the collection ofFileInfo
objects before the whole collection is returned.- When you use
GetFiles
, you must wait for the whole array ofFileInfo
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:
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.
回答4:
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
回答5:
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.