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

FolderSize

Using LINQ, gets the total size of a specified folder. It can also check sizes of subdirectory under it as a parameter.

Source

using System.IO;

public static class MyExtension
{
	public static long FolderSize(this DirectoryInfo dir, bool bIncludeSub)
	{
		long totalFolderSize = 0;

		if (!dir.Exists) return 0;

		var files = from f in dir.GetFiles()
					select f;
		foreach (var file in files) totalFolderSize += file.Length;

		if (bIncludeSub)
		{
			var subDirs = from d in dir.GetDirectories()
						  select d;
			foreach (var subDir in subDirs) totalFolderSize += FolderSize(subDir, true);
		}

		return totalFolderSize;
	}
}

Example

path = @"D:\INCOMING\Books";
var size = new DirectoryInfo(path).FolderSize(true);
Console.WriteLine("Size of {0} is {1}", path, size);

// you can format the size return by using my other extension method, FormatSize()
// var size = new DirectoryInfo(path).FolderSize(true).FomatSize();

Author: Earljon Hidalgo

Submitted on: 28 mrt. 2008

Language: C#

Type: System.Int64

Views: 4934