开发者

Getting biggest directory size on hard disk in code

开发者 https://www.devze.com 2023-02-19 00:57 出处:网络
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 dire

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:\\");
f开发者_如何转开发or (int i = 0; i < count.Length; i++)
{
   // I need to look in each directory and repeat process
}


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.


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.


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.


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.


You could just install cygwin and do:

$ du /cygdrive/c
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号