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

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

Leave a Comment