A Directory Tree Sizer in C#

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

Advertisement
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s