C# Program to Estimate the Size of Folder
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.
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.
Total folder size in bytes: 860474