0 Comments

For some reason, you cannot retrieve the total size of a directory in .NET, including subdirectories, without a workaround. I always found it odd, that some of the most basic features is not implemented in the .NET CLR by default. The list is very short though, since the CLR is huge. I already wrote about the missing Visual Basic functions in C#. Here is another little helpful method that returns the total size of a directory in bytes

private double size = 0;

private double GetDirectorySize(string directory)
{
    foreach (string dir in Directory.GetDirectories(directory))
    {
        GetDirectorySize(dir);
    }

    foreach (FileInfo file in new DirectoryInfo(directory).GetFiles())
    {
        size += file.Length;
    }

    return size;
}

You can then call this method like any other. In ASP.NET you might want to write it to the response stream like this:

Response.Write(this.GetDirectorySize(@"C:\websites\dotnetslave"));