9.4 Calculate the Size of a Directory


9.4 Calculate the Size of a Directory

Problem

You need to calculate the size of all files contained in a directory (and optionally , its subdirectories).

Solution

Examine all the files in a directory, and add together their FileInfo.Length properties. Use recursive logic to include the size of files in contained subdirectories.

Discussion

The DirectoryInfo class does not provide any property that returns size information. However, you can easily calculate the size of all files contained in a directory using the FileInfo.Length property.

Here's a method that uses this technique and optionally examines contained directories recursively:

 using System; using System.IO; public class FileSystemUtil {     public static long CalculateDirectorySize(DirectoryInfo directory,       bool includeSubdirectories) {         long totalSize = 0;         // Examine all contained files.         FileInfo[] files = directory.GetFiles();         foreach (FileInfo file in files) {             totalSize += file.Length;         }         // Examine all contained directories.         if (includeSubdirectories) {             DirectoryInfo[] dirs = directory.GetDirectories();             foreach (DirectoryInfo dir in dirs) {                 totalSize += CalculateDirectorySize(dir, true);             }         }         return totalSize;     } } 

Here's a simple test application:

 using System; using System.IO; public class CalculateDirSize {     private static void Main(string[] args) {         if (args.Length == 0) {             Console.WriteLine("Please supply a directory path.");             return;         }         DirectoryInfo dir = new DirectoryInfo(args[0]);         Console.WriteLine("Total size: " +            FileSystemUtil.CalculateDirectorySize(dir, true).ToString() +            " bytes.");         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net