C# Code Examples

Calculate the Size of a Directory in C#

Calculate Directory Size in C#: By default, we cannot directly retrieve the total size of a directory in .NET, including subdirectories. So how to find the directory size in C# ,VB.NET or any other .NET language?

We need to have a workaround method that will return the total size of a directory in bytes.Here we need to write a method to calculate the total size of a directory. It considers each file and get the total bytes of all files. This is useful for compression or file transfers. We need to determine the size of a directory.

Here is source code to Calculate the Size of Folder in the C# Program

public static long GetDirectorySize(DirectoryInfo dirInfo, bool isAddSubDir)
{
   // Enumerate all the files
   long dirSize = dInfo.EnumerateFiles().Sum(file => file.Length);

   //Include Subdirectories also,if needed
   if (isAddSubDir)
   {
      // Enumerate all sub-directories
      totalSize += dInfo.EnumerateDirectories().Sum(dir => DirectorySize(dir, true));
   }
   return dirSize ;
}
Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

1 year ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

1 year ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

1 year ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

1 year ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

1 year ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

1 year ago