Calculate the Directory Size using c#

By j Miracle

Here i will show how you can get the total size of directory in c#

You can make use of this function:

        static long CalculateDirectorySize(DirectoryInfo directory,  bool includeSubdirectories)
        {
            long totalSize = 0;
             // Examine all contained files.
            foreach (FileInfo file in directory.EnumerateFiles())
            {
                totalSize += file.Length;
            }
            // Examine all contained directories.
            if (includeSubdirectories)
             {
                 foreach (DirectoryInfo dir in directory.EnumerateDirectories())
                {
                    totalSize += CalculateDirectorySize(dir, true);
                 }
             }
             return totalSize;

        }

How to call:

           DirectoryInfo dir = new DirectoryInfo("c:\\windows");
            long size = CalculateDirectorySize(dir, true);
            MessageBox.Show(size.ToString() + " Bytes");

Calculate the Directory Size using c#  (1354 Views)