ADVERTISEMENT
ADVERTISEMENT

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

Here, we are going to learn how to get the size of a specified folder including sub-folder in C#?
Submitted by Nidhi, on September 19, 2020

Here we will read the size of the specified folder in gigabytes including sub-folder.

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.

C# Files Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.