![]() |
VOOZH | about |
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:
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:
Output:
Total folder size in bytes: 860474