troubleshooting Question

Finding the largest file in the directory

Avatar of techbro
techbroFlag for United States of America asked on
9 Comments5 Solutions1179 ViewsLast Modified:
I am studying for MCTS exam, and coding the largest file in the directory in the practice test.
The problem I am facing is in Line 43, which contains the maximum file size. This code is giving me all name and file sizes, but I only need to largest one. If I place the line 43 after the loop, then variables will be out of scope/unreachable. What changes do I need to make to get only one largest file for each folder?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DrivesFolders
    //Populate with the local computer's drives, folders, and files
    class Program
        static void Main(string[] args)
         //   foreach (DriveInfo di in DriveInfo.GetDrives())
           //     Console.WriteLine(" {0}   ({1})", di.Name, di.DriveType);
           //     DirectoryInfo dir = new DirectoryInfo(@di.Name);
                DirectoryInfo dir = new DirectoryInfo(@"C:\");
                foreach (DirectoryInfo dirinfo in dir.GetDirectories())
                    foreach (FileInfo fi in dirinfo.GetFiles())
                        long max=0;
                   //     long min =0;
                        string maxLength ="";
                        if (fi.Length > max)
                            maxLength = fi.Name;
                            max = fi.Length;
                        Console.WriteLine("{0}   ({1})", maxLength, max);
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 5 Answers and 9 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 5 Answers and 9 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros