user586399
user586399

Reputation:

Getting biggest directory size on hard disk in code

I have some troubles in my machine. My harddisk is about 500 GBs, and I am sure my files are no more than 150 GB. But it shows that the free space is only 100 GB. I would know what is the biggest directory in my computer, because when I tried searching with "*.*" size:gigabytes property it doesn't matter. I need an idea of an algorithm that searches in directory then in its subdirectories? e.g.

long count = Directory.GetDirectories("C:\\");
for (int i = 0; i < count.Length; i++)
{
   // I need to look in each directory and repeat process
}

Upvotes: 1

Views: 518

Answers (5)

user3509406
user3509406

Reputation: 409

I also recommend you to try to use WinDirStat, which is open-source software. I share my experience on using this utility here, http://lazyswamp.blogspot.kr/2014/11/windirstat-for-finding-files-big-but.html.

Upvotes: 2

vcsjones
vcsjones

Reputation: 141638

Here is a starting point, it will recursively call the C: drive and calculate the size of each folder. You may want to change it to suit your needs, like rather than keep a dictionary, just keep the biggest one.

Func<DirectoryInfo, long> calc = null;
var sizes = new Dictionary<string, long>();
calc = di =>
            {
                var childSum = di.GetDirectories().Sum(d => calc(d));
                var size = di.GetFiles().Sum(f => f.Length);
                sizes.Add(di.FullName, childSum + size);
                return size;
            };
calc(new DirectoryInfo("C:\\"));

EDIT: To Hans point, you may want to run the program with elevated permissions to snoop in directories you might not have access to, like System Volume Information.

Upvotes: 1

Dave White
Dave White

Reputation: 3461

Do you need to build a program to do this, or are you just trying to use code to figure this out for your own machine?

If it is the later, WinDirStat will save you a lot of time.

If it is the former, I suggest you look into recursive functions.

Upvotes: 2

Daren Thomas
Daren Thomas

Reputation: 70324

You could just install cygwin and do:

$ du /cygdrive/c

Upvotes: 0

John Fisher
John Fisher

Reputation: 22719

You'll either need to learn about recursion or use a Stack.

I could write out the code for you, but if you plan to write programs more often, these are essential concepts to understand. Put in a bit of effort to understand them well. Then, you'll be able to do this task as well as many others.

Upvotes: 3

Related Questions