Finding your largest file

I had a recent project where I had to loop though a directory and then any subdirectory and pull out any .jar files to stick onto a class path…. Man, java sucks.  In any event, I whipped this code, which I then modified to find the largest file on my file system.  Kinda handy – if my hard drive space starts creeping up:

static void Main(string[] args)
{
    Console.WriteLine("Start");
    string startingPath = @"C:\Users";
    List<FileInfo> fileInfos = GetFileInfos(new DirectoryInfo(startingPath));
    Console.WriteLine("{0} files found", fileInfos.Count);
    FileInfo largestFile = fileInfos.FirstOrDefault(f => f.Length == fileInfos.Max(t => t.Length));
    Console.WriteLine("{0} is the largest with {1} bytes", largestFile.Name, largestFile.Length);
    Console.WriteLine("End");
    Console.ReadKey();
}

static List<FileInfo> GetFileInfos(DirectoryInfo directoryInfo)
{
    List<FileInfo> fileInfos = null;
    try
    {
        fileInfos = directoryInfo.GetFiles().ToList();
        foreach (DirectoryInfo currentDirectoryinfo in directoryInfo.GetDirectories())
        {
            try
            {
                fileInfos.AddRange(GetFileInfos(currentDirectoryinfo));
            }
            catch (ArgumentNullException)
            {
            }
            catch (PathTooLongException)
            {
            }
        }
    }
    catch (UnauthorizedAccessException)
    {

    }


    return fileInfos;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: