search
HomeBackend DevelopmentC#.Net TutorialC# program estimates folder size

C# 程序估计文件夹的大小

Introduction

In this article, we will look at a C# program to estimate folder size. On our computers, we store files in directories called folders. We will also see how to estimate the size of the folders present in the files. Merely calculating the file size is not sufficient to achieve our goals. Instead, we also need to calculate the size of folders and subfolders.

The following article will be divided into three parts to explain how to calculate the size of the folder. The first part we need to know is the GetFolderSize method, which will give us the size of the folder. The second part is the FormatBytes method, which converts the size into a human-readable format. We will also briefly look at different approaches, which will be crucial for the further development of this article.

method

We will learn five methods that we will use in code to calculate the size of a folder.

  • DirectoryInfo(dir_path) - This method takes a directory path as an input parameter and returns its information, such as information about its files, subfolders, and subdirectories.

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

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

  • GetDirectories() This method will work best in our code because it returns all folders, subfolders for a single file and subdirectories.

In addition to these methods that will be used directly in our code, there is another important method considering the output console.

  • FormatBytes() The size taken out by the length method is in bytes. It is not in a human-readable format, so it needs to be converted to Correct string format, we need to convert it using FormatBytes method. The method takes bytes as input, converts them to MB or KB as needed, then rounds to two decimal places and converts to a string.

We will also look at how the DirectoryInfo class works and its use in code.

It allows a variety of operations to be performed on files or directories. One can use this class to create, move, and delete files. It is located under the System.Io namespace. It even provides methods for working with files.

algorithm

Step 1 We must first put all the files in one location. Here we store all files in all files variable.

Step 2 Now we will move to all the files by iterating through the loop and calculating the length of each file via the Length method.

Step 3 Now we have to make sure that no subdirectories, subfolders, and folders that exist in the file are left behind.

Step 4 We recursively move to each file and check if it contains any subdirectories, subfolders, or folders.

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

Step 6 Now we have to make sure to use the format bytes method in order to convert the final answer into a human readable format, converting it from the byte size in string format.

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

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 iterate over is the recursive loop. In this recursive loop, we see that we just iterate until we reach all subfolders, files, directories, subdirectories, and folders. So the time complexity is O(file size). Apart from this, all other methods only take constant time complexity. This constitutes a time complexity of O(1) in Big-O notation. So the final time complexity is just the total size of the folder.

in conclusion

In this article, we have extensively discussed how to calculate the size of a folder. We learn about the different methods and classes used in our code. We also learned that we can't draw conclusions just by counting file sizes. We must also make sure to calculate the size of all folders, directories, subdirectories, and subfolders. We also learned about the algorithm of the code, the code itself, and the time complexity. We hope this article has been helpful in enhancing your knowledge of C#.

The above is the detailed content of C# program estimates folder size. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.