find the size of a directory in csharp

You can find the size of a directory by iterating over all the files and subdirectories under it and summing up their sizes. Here is a code snippet that demonstrates how to do that:

main.cs
using System.IO;

public static long GetDirectorySize(string directoryPath)
{
    DirectoryInfo directory = new DirectoryInfo(directoryPath);
    long size = 0;
    foreach (FileInfo file in directory.GetFiles("*.*", SearchOption.AllDirectories))
    {
        size += file.Length;
    }
    return size;
}
307 chars
13 lines

This method takes a directory path as input and returns the total size of all files under it in bytes. It uses the DirectoryInfo class to get a list of all files and subdirectories under the specified directory, and then iterates over each file and adds its size to the total size. The SearchOption.AllDirectories parameter tells GetFiles to recursively search all subdirectories.

gistlibby LogSnag