Subscribe

RSS Feed (xml)

Calculate the Size of Directory

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

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail