Calculate Folder/Directory Size

Programming LINQ C#

Here’s how to get ("calculate") the size of a folder using .NET 4 and LINQ. The code also includes the size of all sub-directories.

using System;
using System.IO;
using System.Linq;

namespace ConsGetDirSize
{
internal class Program
{
private static long DirectorySize(DirectoryInfo dInfo, bool includeSubFolders)
{
// enumerate all the files
long totalSize = dInfo.EnumerateFiles()
.Sum(file => file.Length);

// if SubDirectories should be included
if (includeSubFolders)
{
// enumerate all sub-directories
totalSize += dInfo.EnumerateDirectories()
.Sum(dir => DirectorySize(dir, true));
}
return totalSize;
}

private static void Main(string[] args)
{
DirectoryInfo dInfo = new DirectoryInfo(@"E:\Videos");

// set bool parameter to false if you do not want to include subdirectories.
long sizeOfDir = DirectorySize(dInfo, true);

Console.WriteLine("Directory size in Bytes : " + "{0:N0} Bytes", sizeOfDir);
Console.WriteLine("Directory size in KB : " + "{0:N2} KB", ((double)sizeOfDir) / 1024);
Console.WriteLine("Directory size in MB : " + "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));
Console.WriteLine("Directory size in GB : " + "{0:N2} GB", ((double)sizeOfDir) / (1024 * 1024 * 1024));
Console.ReadLine();
}
}
}

Thanks to DirectoryInfo.EnumerateDirectories and DirectoryInfo.EnumerateFiles you don't have to iterate for yourself over all the files, getting the size of the directory content within the blink of an eye.