Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# calculating directory size

C# noob here, I'm trying to conduct an application to calculate the size of directories. Using this as an example, I created bellow method to do so:

public static long CalculateSize(DirectoryInfo dir, string search = "*.*")
{
    long result = 0;
    FileInfo[] files = null;
    DirectoryInfo[] subDirs = null;
    try
    {
        files = dir.GetFiles(search, SearchOption.TopDirectoryOnly);
    }

    catch (UnauthorizedAccessException)
    {
        //catch unauthorized exception
    }

    catch (PathTooLongException e)
    {
        Console.WriteLine("PATH: " + e.Message);
    }

    if (files != null)
    {
        foreach (var file in files)
        {
            result += file.Length;                    
        }

        subDirs = dir.GetDirectories(search, SearchOption.TopDirectoryOnly);
        foreach (var directory in subDirs)
        {
            result += CalculateSize(directory, search);
        }
    }
    return result;
}

Although when I run this with:

var dir = new DirectoryInfo("C:\\Users\\");
var size = FileSystem.CalculateSize(dir);
Console.WriteLine(size);

I get nearly double the size, File Explorer shows me: my result -> 33189002865 file explorer properties -> 12263901898 I tested this, replacing "result += file.Length" with "result++" to get the number of files the method iterates over and got large difference there as well: my result -> 94476 file expl -> 59318

When I test this on my other drive (D:) I get absolutely the same result as File Explorer, regardless if I run this on my root, some folder inside, etc. But whenever I test on my system drive (C:) - get this strange results. I have no idea what I am doing wrong and would be thankful for your assistance!

P.S. I run my tests on Windows 10 Pro 64bit, if that's relevant.

like image 298
Petar Stoyanov Avatar asked Mar 17 '26 02:03

Petar Stoyanov


1 Answers

It's a problem with File explorer algorithm of sizing or permissions to some specifics folders.

File explorer for path:

C:\Users\All Users

Won't show any informations like size.

So if you will check this path:

C:\Users\

It won't count size of "C:\Users\All Users" . But your script will count size of it.

Better windows tool for getting size of folders is DIR in cmd.

Open your cmd, and write this:

cd Users
dir /s /a

/s - shows all the files and folders in the specified directory

/a - shows all types of files and folders

(Sorry for Polish language)

Picture of good calculations for C:\Users\ (Your program and dir /s /a):

Picture of good calculations

What shows file explorer for C:\Users\ :

What shows file explorer

like image 50
Maciej Pulikowski Avatar answered Mar 19 '26 15:03

Maciej Pulikowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!