I would like to optimize the following method, that returns the total file count of the specified folder and all subfolders, for speed and memory usage; any advice is appreciated.
Thanks.
private int countfiles(string srcdir)
{
try
{
DirectoryInfo dir = new DirectoryInfo(srcdir);
//if the source dir doesn't exist, throw an exception
if (!dir.Exists)
throw new ArgumentException("source dir doesn't exist -> " + srcdir);
int count = dir.GetFiles().Length;
//loop through each sub directory in the current dir
foreach (DirectoryInfo subdir in dir.GetDirectories())
{
//recursively call this function over and over again
count += countfiles(subdir.FullName);
}
//cleanup
dir = null;
return count;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return 0;
}
}
So I did some benchmarking with the suggestions that were proposed. Here are my findings:
-
My method, with recursion, is the slowest finding 9062 files in a directory tree in 6.234 seconds.
-
@Matthew’s answer, using SearchOption.AllDirectories, is the fastest finding the same 9062 files in 4.546 seconds
-
@Jeffery’s answer, using LINQ, is in the middle of the pack finding the same 9062 files in 5.562 seconds.
Thank you everyone for your suggestions.
Could you not change the entire method to: