Calculate the Size of a Directory - CSharp File IO

CSharp examples for File IO:Directory

Description

Calculate the Size of a Directory

Demo Code


using System;//  w w  w.jav  a  2  s. co  m
using System.IO;

    static class MainClass
    {
        static void Main(string[] args)
        {
            DirectoryInfo dir = new DirectoryInfo("c:/a");
            Console.WriteLine("Total size: " + CalculateDirectorySize(dir, true).ToString() + " bytes.");
        }

        static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories)
        {
            long totalSize = 0;

            foreach (FileInfo file in directory.EnumerateFiles())
            {
                totalSize += file.Length;
            }

            if (includeSubdirectories)
            {
                foreach (DirectoryInfo dir in directory.EnumerateDirectories())
                {
                    totalSize += CalculateDirectorySize(dir, true);
                }
            }

            return totalSize;
        }
    }

Result


Related Tutorials