I wrote the following method to determine the max file size:
public static long GetMaxFileSize(string dirPath, long maxFileSize)
{
DirectoryInfo [] dirInfos = new DirectoryInfo(dirPath).GetDirectories();
foreach (DirectoryInfo dirInfo in dirInfos)
{
DirectoryInfo [] subDirInfos = dirInfo.GetDirectories();
foreach (DirectoryInfo subDirInfo in subDirInfos)
maxFileSize = GetMaxFileSize(dirInfo.FullName, maxFileSize);
FileInfo [] fileInfos = dirInfo.GetFiles();
foreach (FileInfo fileInfo in fileInfos)
{
if (maxFileSize < fileInfo.Length)
maxFileSize = fileInfo.Length;
}
}
return maxFileSize;
}
Code Complete recommends to “use recursion selectively”. That being the case, I was wondering if the community thought this was a valid use of recursion. If not, is there a better technique of doing this?
EDIT: I can’t use LINQ because its not available in .NET 2.0, but I don’t want to tag this as a .NET 2.0 question only to further discussion points like Jared’s below.
EDIT: Cleaned up code based on an issue that was spotted in not getting the root directory’s files.
public static long GetMaxFileSize(DirectoryInfo dirInfo, long maxFileSize)
{
DirectoryInfo [] subDirInfos = dirInfo.GetDirectories();
foreach (DirectoryInfo subDirInfo in subDirInfos)
{
maxFileSize = GetMaxFileSize(subDirInfo, maxFileSize);
}
FileInfo [] fileInfos = dirInfo.GetFiles();
foreach (FileInfo fileInfo in fileInfos)
{
if (maxFileSize < fileInfo.Length)
maxFileSize = fileInfo.Length;
}
return maxFileSize;
}
I think a better way is to the File System API to do the searching for you via Directory.GetFiles. This method provides automatic searching of sub-directories. This eliminates the question of whether or not to recurse and instead leaves the decision of how to implement it on the designer of the API (who likely designed it for such a scenario).
This method combined with LINQ provides a very elegant solution
EDIT As Jimmy pointed out, for 4.0 and higher, it’s better to use EnumerateFiles to avoid the overhead of creating a potentially large array