Sunday, 25 August 2013

Linq - Find the size of a Directory

In this article we are going to see the usage of EnumerateFiles and EnumerateDirectories in Linq and how it is working.

EnumerateFiles() : Will enumerate the files present in the folder 
EnumerateDirectories() : Will enumerate the Directory present in the folder.

/* Directory Size*/
   long _size = Size(@"D:\flot", true);
   Console.WriteLine("Directory Size in MB : {0:N2} MB", ((double)_size) / (1024 * 1024));

   static long Size(string path, bool includesubdir)
            DirectoryInfo info = new DirectoryInfo(path);

            long _size = info.EnumerateFiles().Sum(x => x.Length);

            _size+=info.EnumerateDirectories().Sum(x => Size(x.FullName,includesubdir));
            return _size;

Output :

Directory Size in MB : 2.14 MB

No comments:

Post a Comment