To calculate the total size of all files in a directory, including
all subdirectories, you can use DirectoryInfo and recursively enumerate files using
EnumerateFiles() with the SearchOption.AllDirectories option.
Example: Calculate total size (in bytes)
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
string path = @"C:\MyFolder";
long totalSize = GetDirectorySize(path);
Console.WriteLine($"Total size: {totalSize} bytes");
Console.WriteLine($"Total size: {totalSize / 1024.0 / 1024.0:F2} MB");
}
static long GetDirectorySize(string folderPath)
{
if (!Directory.Exists(folderPath))
return 0;
return Directory.EnumerateFiles(folderPath, "*", SearchOption.AllDirectories)
.Select(f => new FileInfo(f))
.Sum(fi => fi.Length);
}
}
Notes:
Directory.EnumerateFiles(...) is memory-efficient compared to
GetFiles(...) because it streams results.
This method handles deep nested folders and hidden files.
If you want to ignore certain file types, you can filter them with
.Where(...).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To calculate the total size of all files in a directory, including all subdirectories, you can use
DirectoryInfoand recursively enumerate files usingEnumerateFiles()with theSearchOption.AllDirectoriesoption.Example: Calculate total size (in bytes)
Notes:
Directory.EnumerateFiles(...)is memory-efficient compared toGetFiles(...)because it streams results..Where(...).Optional: Handle exceptions (e.g., permission errors)
Wrap file access in try-catch if you expect restricted folders: