Skip to content
Related Articles

Related Articles

C# Program to Estimate the Size of Folder

View Discussion
Improve Article
Save Article
  • Last Updated : 20 Dec, 2021
View Discussion
Improve Article
Save Article

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#




// C# program to find the estimate size of the folder
using System;
using System.IO;
  
class GFG{
  
// Driver code
static public void Main()
{
      
    // Get the directory information using directoryInfo() method
    DirectoryInfo folder = new DirectoryInfo("D://d2c articles");
      
    // Calling a folderSize() method
    long totalFolderSize = folderSize(folder);
      
    Console.WriteLine("Total folder size in bytes: "
                      totalFolderSize);
}
  
// Function to calculate the size of the folder
static long folderSize(DirectoryInfo folder)
{
    long totalSizeOfDir = 0;
      
    // Get all files into the directory
    FileInfo[] allFiles = folder.GetFiles();
      
    // Loop through every file and get size of it
    foreach (FileInfo file in allFiles)
    {
        totalSizeOfDir += file.Length;
    }
      
    // Find all subdirectories
    DirectoryInfo[] subFolders = folder.GetDirectories();
      
    // Loop through every subdirectory and get size of each
    foreach (DirectoryInfo dir in subFolders)
    {
        totalSizeOfDir += folderSize(dir);
    }
      
    // Return the total size of folder
    return totalSizeOfDir;
}
}


Output:

Total folder size in bytes: 860474

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!