Well, I was holding back on posting an example using Linq, but now that my esteemed colleague, Richard MacCutchan, has posted one (it is very probable I esteem him much more than he esteems me):
using System.IO;
using System.Linq;
private void SomeButton_Click(object sender, EventArgs e)
{
FileInfo longestFile = null;
string filter = @"*.*";
SearchOption searchType = SearchOption.AllDirectories;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
longestFile = new DirectoryInfo(folderBrowserDialog1.SelectedPath)
.EnumerateFiles(filter, searchType)
.OrderByDescending(fil => fil.Length)
.FirstOrDefault();
}
Console.WriteLine("Longest File: {0} Length: {1}", longestFile.FullName, longestFile.Length);
}
Note: the 'SearchOption.AllDirectories flag is what makes the search recursive. Do read the MSDN docs for the interesting aspects/behaviors of 'EnumerateFiles compared to using 'GetFiles: [
^]: "Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient."