Computing the size of a folder

 
 
  • Gérald Barré

The .NET framework does not provide a built-in function to compute the total size of all files in a folder and its subfolders. It is straightforward to implement, so here's the code:

C#
public static long FolderSize(string path)
{
    long size = 0;
    DirectoryInfo directoryInfo = new DirectoryInfo(path);
    IEnumerable<FileInfo> files = directoryInfo.GetFiles("*", SearchOption.AllDirectories);
    foreach (FileInfo file in files)
    {
        size += file.Length;
    }

    return size;
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?