C# Program to Estimate the Size of Folder
Last Updated :
20 Dec, 2021
The size of the folder is a sum of the size of files and subfolders included in the folder. Here, we will learn to calculate the size of any directory using C#. To calculate the size of the folder we use the following methods:
- DirectoryInfo(dir_path): It takes a directory path as an argument and returns information about its files and subdirectories.
- GetFiles(): This method returns the names of all the files of a single directory.
- GetDirectories(): This method returns all the subfolders or subdirectories of a single directory.
- Length: It calculates the size of the current file in bytes.
Approach:
1. Create a method that is used to find the estimated size of the file. In this method:
Get all files in the current directory using
FileInfo[] allFiles = folder.GetFiles();
Loop through each and every files present in the given folder to calculate their length.
foreach (FileInfo file in allFiles)
totalSizeOfDir += file.Length;
If a subdirectory is found get it.
DirectoryInfo[] subfolders = folder.GetDirectories();
Now calculate the size of every subdirectory recursively.
foreach (DirectoryInfo dir in subfolders)
totalSizeOfDir = folderSize(dir);
2. In the main method, first we get the directory information then we call the folderSize method to find the estimated size of the specified folder and display the output.
Example:
C#
using System;
using System.IO;
class GFG{
static public void Main()
{
DirectoryInfo folder = new DirectoryInfo( "D://d2c articles" );
long totalFolderSize = folderSize(folder);
Console.WriteLine( "Total folder size in bytes: " +
totalFolderSize);
}
static long folderSize(DirectoryInfo folder)
{
long totalSizeOfDir = 0;
FileInfo[] allFiles = folder.GetFiles();
foreach (FileInfo file in allFiles)
{
totalSizeOfDir += file.Length;
}
DirectoryInfo[] subFolders = folder.GetDirectories();
foreach (DirectoryInfo dir in subFolders)
{
totalSizeOfDir += folderSize(dir);
}
return totalSizeOfDir;
}
}
|
Output:
Total folder size in bytes: 860474
Share your thoughts in the comments
Please Login to comment...