I am looking for a faster way to get the total size of all files in subfolders with over 75,000 files with C#. The following takes about 8 seconds on my laptop with an SSD drive.
FileInfo[] files;
long fileMBs;
files = di.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo fi in files)
{
fileMBs += fi.Length;
}
I looked into using Win32 CreateFile and GetFileSize, but could not find examples on how to call them from C#. Would this be faster if called for each file given its full path? If so, I do I use them from C#? Is there a faster way?
I did a number of various tests. The test folder was created by extracting a Drupal 10 tar.gz 3 times at different depths. Each Drupal 10 installation has a bit over 25,000 files.
My limited excursion into Win32 was very slow, not a starter, and not considered worth my effort to understand why.
Using LINQ was the next slowest.
My testing, showed this is the fastest way, assuming path is the full path to a directory:
Don't have the energy to post all the testing code. Tried LINQ, simple foreach as above, and a full recursion algorithm. The simple foreach was the fastest. Each test was run after a laptop shutdown for at least 30 seconds to clear the cache. Simple timing using DateTime start, end. Just an eyeball of what might make a difference.