Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a directory size (files in the directory) in C#?

I want to be able to get the size of one of the local directories using C#. I'm trying to avoid the following (pseudo like code), although in the worst case scenario I will have to settle for this:

    int GetSize(Directory)
    {
        int Size = 0;

        foreach ( File in Directory )
        {
            FileInfo fInfo of File;
            Size += fInfo.Size;
        }

        foreach ( SubDirectory in Directory )
        {
            Size += GetSize(SubDirectory);
        }
        return Size;
    }

Basically, is there a Walk() available somewhere so that I can walk through the directory tree? Which would save the recursion of going through each sub-directory.

like image 478
Lloyd Powell Avatar asked Jul 13 '09 09:07

Lloyd Powell


People also ask

How do you get the size of the files in a directory in C?

Use the stat Function to Get File Size in C It takes two arguments - the first of which is the char pointer that should point to the file's pathname, and the second argument is of type struct stat pointer which is described extensively in the function manual.

How do I get a list of folder sizes?

Open a file explorer window and right-click on the 'Name' field at the top. You'll see some options – specifically, options, that let you pick what sort of info you want to see about your folders. Select Size and the property will appear on the far right of your window.


2 Answers

A very succinct way to get a folder size in .net 4.0 is below. It still suffers from the limitation of having to traverse all files recursively, but it doesn't load a potentially huge array of filenames, and it's only two lines of code. Make sure to use the namespaces System.IO and System.Linq.

private static long GetDirectorySize(string folderPath)
{
    DirectoryInfo di = new DirectoryInfo(folderPath);
    return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
}
like image 86
Kev Avatar answered Sep 28 '22 01:09

Kev


If you use Directory.GetFiles you can do a recursive seach (using SearchOption.AllDirectories), but this is a bit flaky anyway (especially if you don't have access to one of the sub-directories) - and might involve a huge single array coming back (warning klaxon...).

I'd be happy with the recursion approach unless I could show (via profiling) a bottleneck; and then I'd probably switch to (single-level) Directory.GetFiles, using a Queue<string> to emulate recursion.

Note that .NET 4.0 introduces some enumerator-based file/directory listing methods which save on the big arrays.

like image 43
Marc Gravell Avatar answered Sep 28 '22 01:09

Marc Gravell