Q:

C# program to get the size of a specified folder including sub-folder

belongs to collection: C# Files Programs

0

C# program to get the size of a specified folder including sub-folder

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to get the size of a specified folder including sub-folder is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to get the size of a specified folder 
//including sub-folder.

using System;
using System.Linq;
using System.IO;

class Demo
{
    static long GetSizeOfFolder(DirectoryInfo dInfo, bool isSubFolder)
    {
        long sizeInBytes = dInfo.EnumerateFiles().Sum(file => file.Length);

        if (isSubFolder == true)
            sizeInBytes += dInfo.EnumerateDirectories().Sum(dir => GetSizeOfFolder(dir, true));

        return sizeInBytes;
    }

    static void Main(string[] args)
    {
        long sizeOfDir;
        double sizeGb;

        DirectoryInfo dInfo = new DirectoryInfo(@"D:/movie");
        sizeOfDir = GetSizeOfFolder(dInfo, true);
        sizeGb = ((double)sizeOfDir) / (1024*1024*1024);

        Console.WriteLine("Size of folder including sub-folder in GB: "+sizeGb);
    }
}

Output:

Size of folder including sub-folder in GB: 14.6635034512728
Press any key to continue . . .

Explanation:

Here, we created a class Demo that contains two static methods GetSizeOfFolder() and Main(). Here we get the size of the specified folder including the sub-folder using DirectoryInfo class with LINQ Sum() and EnumerateFiles() methods. It returns the size of the folder in bytes then we converted the number of bytes into gigabytes by dividing by (1024*1024*1024), then print size into gigabytes on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# program to demonstrate the BinaryReader and Bin... >>
<< C# program to demonstrate MemoryStream class...