The C# code below, when run, calculates the size of a given directory and all its subdirectories.
using System; using System.Collections.Generic; using System.IO; namespace DirectoryTreeSizer { class Program { static void Main(string[] args) { Console.WriteLine("Program begins: " + DateTime.Now.ToString()); var directoryPathToStartIn = (args.Length > 0 ? args[0] : "."); var directoryTreeSizer = new DirectoryTreeSizer(directoryPathToStartIn); var directorySizeTree = directoryTreeSizer.BuildDirectorySizeTree(); Console.WriteLine("Program ends: " + DateTime.Now.ToString()); } } class DirectoryTreeSizer { private string _directoryPathToStartIn; public DirectoryTreeSizer(string directoryPathToStartIn) { _directoryPathToStartIn = directoryPathToStartIn; } public DirectoryNode BuildDirectorySizeTree() { var directoryToStartInNode = new DirectoryNode(this._directoryPathToStartIn); directoryToStartInNode.CalculateSizeWithAllDescendants(); return directoryToStartInNode; } } class DirectoryNode { private string _path; private long _sizeInBytes; private List _children; public DirectoryNode(string path) { this._path = path; this._sizeInBytes = 0; this._children = new List(); } public void CalculateSizeWithAllDescendants() { var directoryInfo = new DirectoryInfo(this._path); var files = directoryInfo.GetFiles(); foreach (var file in files) { var fileSizeInBytes = file.Length; this._sizeInBytes += fileSizeInBytes; } var subdirectories = directoryInfo.GetDirectories(); foreach (var subdirectory in subdirectories) { var subdirectoryAsTreeNode = new DirectoryNode(subdirectory.FullName); subdirectoryAsTreeNode.CalculateSizeWithAllDescendants(); this._children.Add(subdirectoryAsTreeNode); this._sizeInBytes += subdirectoryAsTreeNode._sizeInBytes; } Console.WriteLine(this._path + ":" + this._sizeInBytes); } } }