Earlier today, I posted a method that returns the total size of a directory, including all subdirectories. It returns the bytes and not kilobytes, megabytes or gigabytes, so I write a little formatting method to do just that.

private string SizeFormat(float size, string formatString)
{
    if (size < 1024)
        return size.ToString(formatString) + "bytes";

    if (size < Math.Pow(1024, 2))
        return (size / 1024).ToString(formatString) + " kb";

    if (size < Math.Pow(1024, 3))
        return (size / Math.Pow(1024, 2)).ToString(formatString) + " mb";

    if (size < Math.Pow(1024, 4))
        return (size / Math.Pow(1024, 3)).ToString(formatString) + " gb";

    return size.ToString(formatString);
}

The method take a size and a formatString parameter. The formatString parameter is for the formatting of the numbers themselves. You can format them to contain decimals or separators or whatever you please. This is how to call the method so it returns decimals:

SizeFormat(3210540, "N")

This method call returns this string: "3,14 MB"

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"));