ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

GetSize

This method extends the DirectoryInfo class to return the size in bytes of the directory represented by the DirectoryInfo instance.

Source

public static long GetSize(this DirectoryInfo dir)
{
    long length = 0;
    
    // Loop through files and keep adding their size
    foreach (FileInfo nextfile in dir.GetFiles())
        length += nextfile.Exists ? nextfile.Length : 0;

    // Loop through subdirectories and keep adding their size
    foreach (DirectoryInfo nextdir in dir.GetDirectories())
        length += nextdir.Exists ? nextdir.GetSize() : 0;

    return length;
}

Example

DirectoryInfo WindowsDir = new DirectoryInfo(@"C:\WINDOWS");
long WindowsSize = WindowsDir.GetSize();

Author: Joel Rosario Mathias

Submitted on: 13 feb 2010

Language: C#

Type: System.IO.DirectoryInfo

Views: 5148