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 ; }
Leave a Reply