Get Directory Size - C# | Coding Cluster - using, c#, mvc 4, iphone, php, ios, javascript, in mvc 3 & more

Get Directory Size - C#


 Get Directory Size In Bytes,KB,and MB using C#

     Calculate the Size of a Folder/Directory using .NET 4.0   
                                 .NET 4.0 introduces 7 New methods to Enumerate Directory and Files in .NET 4.0.
All these methods return Enumerable Collections (IEnumerable<T>), which perform better   than  arrays. We will be using the DirectoryInfo.EnumerateDirectories and DirectoryInfo. EnumerateFiles in this sample which returns an enumerable collection of Directory and File information respectively.    
Here's how to calculate the size of a folder or directory using .NET 4.0 and LINQ. The code also   calculates the size of all sub-directories.

    Calculate the Size of a Folder/Directory using C#
    using System;
    using System.Linq;
    using System.IO;
    namespace DirectoryInfo
      class Program
        static void Main(string[] args)
          DirectoryInfo dInfo = new DirectoryInfo(@"Your folder path here");
          // set bool parameter to false if you
          // do not want to include subdirectories.
          long sizeOfDir = DirectorySize(dInfo, true);
          Console.WriteLine("Directory size in Bytes : " +
          "{0:N0} Bytes", sizeOfDir);
          Console.WriteLine("Directory size in KB : " +
          "{0:N2} KB", ((double)sizeOfDir) / 1024);
          Console.WriteLine("Directory size in MB : " +
          "{0:N2} MB", ((double)sizeOfDir) / (1024 * 1024));
        static long DirectorySize(DirectoryInfo dInfo, bool includeSubDir)
           // Enumerate all the files
           long totalSize = dInfo.EnumerateFiles()
                        .Sum(file => file.Length);
           // If Subdirectories are to be included
           if (includeSubDir)
              // Enumerate all sub-directories
              totalSize += dInfo.EnumerateDirectories()
                       .Sum(dir => DirectorySize(dir, true));
           return totalSize;


Anonymous said...

Even run as admin it throws an exception when it hits files in the rectcle bin or documents and settings folder. Is there a clean workaround?

Anonymous said...

Try this link

Post a Comment

Share your thoughts here...




Blogger Widgets