Home »
.Net »
C# Programs
C# - Get the size of a folder including sub-folder
Learn, how to get the size of a specified folder including sub-folder in C#?
By Nidhi Last updated : April 03, 2023
Problem Statement
Here, we will read the size of the specified folder in gigabytes including sub-folder.
C# program to get the size of a specified folder including sub-folder
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 »