C# Program to Estimate the Size of Folder


Introduction

In this article, we will understand the C# program to estimate the size of a folder. On our PC, we store files in a directory called a folder. We will also be understanding how to estimate the size of folders that are present inside a file. Calculation of just file size is not enough to reach our goal. Instead we need to calculate the size of folders and subfolders too.

The article below will explain to calculate the size of the folder in three parts. The first part we will know will be the GetFolderSize method which will be giving us the size of the folders. The second part will be the FormatBytes method which will convert the sizes into human-readable format. We will also be understanding different methods briefly which will be of utmost importance while moving further in the article.

Methods

We will be learning about five methods that we are going to use in our code to calculate the size of the folder.

  • DirectoryInfo(dir_path) − This method takes the directory path as input parameters and returns their information such as about its files and subfolders and subdirectories.

  • GetFiles()  It returns the name of all the files of a single directory.

  • Length  It returns the size of the files in bytes.

  • GetDirectories()  This method will be of utmost use in our code as it returns all the folders, subfolders, and subdirectories of a single file.

Apart from these methods which will be used directly in our code, there is one more method that is important considering the output console.

  • FormatBytes()  The size taken out by the length method is in bytes and it is not in a human-readable format so to convert it into proper string format we need to convert it using the FormatBytes method. This method takes bytes as input and converts it into MB or KB depending upon the demand and then rounds off to two decimal places and converts it into a string.

We will also get an idea of how DirectoryInfo class works and its uses in our code.

It allows one to perform multiple operations with the file or directory. One can create, move, and delete files using this class. It comes under the System.Io namespace. It even provides methods to work with files.

Algorithm

Step 1  We have to first get all the files in a single place. Here we are storing all the files in the all files variable.

Step 2  Now we will be moving to all the files by iterating in a loop and calculating the length of each file through the Length method.

Step 3  Now we have to make sure that we do not leave behind the subdirectories, subfolders, and folders which are present inside a file.

Step 4  We recursively move toward each file and check whether it contains any subdirectories, subfolders, or folders inside them.

Step 5  We will now calculate each file length whatsoever is present inside it and store it in the total folder size variable.

Step 6  Now we have to make sure to make use of the format bytes method in order to convert the final answer into a human-readable format that converts it from bytes size to string format.

Step 7  Finally, we can print the answer using the console function.

Example

using System;
using System.IO;
Class Tutorials_point{

   // Driver code
   static public void Main() {

      DirectoryInfo folder = new DirectoryInfo("D://d2c articles");
      
      //Here we are getting the complete folder information.
      
      //This is a class that is used to get complete information about directories.
      long totalFolderSize = folderSize(folder);
      
      //here folderSize is called and we are storing the answer
      
      // in the totalFolderSize variable.
      long ans= FormatBytes(totalFolderSize);
      
      //here we are formatting the bytes size into a readable format by
      
      //calling the FormatBytes function.
      Console.WriteLine("Total folder size in bytes: " + ans);
      
      //final ans is printed.
   }
   static long folderSize(DirectoryInfo folder) {
      long totalSizeOfDir = 0;

      // Get all files into the directory
      FileInfo[] allFiles = folder.GetFiles();

      // Loop through every file and get the size of it
      foreach (FileInfo file in allFiles) {
         totalSizeOfDir += file.Length;
         
         // we are calculating the length here.
      }

      DirectoryInfo[] subFolders = folder.GetDirectories();
      
      //here we are finding if there are any subfolders or directories present inside a file.
      foreach (DirectoryInfo dir in subFolders) {
         totalSizeOfDir += folderSize(dir);
         
         //here we are recursively calling to check all the subfolders.
      }
      return totalSizeOfDir;
      
      // we return the total size here.
   }
}
public static string FormatBytes(long bytes) {
   /*This method is basically used to determine the size of the file. It determines first whether we have to complete in bytes or KB or MB or GB. If the size is between 1KB and 1MB, then we will calculate the size in KB. Similarly, if it is between MB and GB, then we will calculate it in MB.*/
   string[] sizes = { "bytes", "KB", "MB", "GB", "TB" };
   
   //here we are storing all sizes in sizes string.
   int order = 0;
   
   // we have initialized the order with zero so that it does not give us some garbage value in return.
   while (bytes >= 1024 && order < sizes.Length - 1) {
      order++;
      bytes /= 1024;
   }
   return $"{bytes:0.##} {sizes[order]}";
}

Output

Total folder size in bytes:850757

Time Complexity

In the code given above, we see that the only loop we are iterating to is a recursive one. In that recursive loop, we see that we are only iterating till we reach all the subfolders, files, directories, subdirectories, and folders. So that makes up a time complexity of O(size of the file). Other than this all other methods take up only constant time complexity. That makes up in Big-O notation time complexity of O(1). Thus, the final time complexity is the total size of the folder only.

Conclusion

In this article we have extensively discussed how to calculate the size of the folder. We understood different methods and classes which came into use in our code. We also learned the fact that just by calculating the file size we can not come to conclusion. We also have to make sure to calculate the size of all the folders, directories, subdirectories, and subfolders too. We also understood the algorithm of the code, the code itself, and the time complexity too. We hope that this article has been useful in enhancing your knowledge about C#.

Updated on: 21-Apr-2023

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements