Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to calculate the Size of Folder using C#?
To calculate the size of a folder in C#, you need to traverse through all files in the folder and its subdirectories, then sum up their sizes. The DirectoryInfo class provides methods to enumerate files and directories, making this task straightforward.
Syntax
Following is the syntax for getting folder information and enumerating files −
DirectoryInfo info = new DirectoryInfo(@"C:\FolderPath");
long size = info.EnumerateFiles("*", SearchOption.AllDirectories).Sum(file => file.Length);
Using DirectoryInfo for Simple Folder Size
The most basic approach uses DirectoryInfo.EnumerateFiles() with SearchOption.AllDirectories to include all subdirectories −
using System;
using System.IO;
using System.Linq;
class Program {
public static void Main() {
string folderPath = @"C:\Windows\System32\drivers";
try {
DirectoryInfo info = new DirectoryInfo(folderPath);
if (info.Exists) {
long totalSize = info.EnumerateFiles("*", SearchOption.AllDirectories)
.Sum(file => file.Length);
Console.WriteLine($"Folder: {folderPath}");
Console.WriteLine($"Total Size: {totalSize} bytes");
Console.WriteLine($"Total Size: {totalSize / (1024 * 1024.0):F2} MB");
} else {
Console.WriteLine("Directory does not exist.");
}
} catch (UnauthorizedAccessException) {
Console.WriteLine("Access denied to some files/folders.");
} catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
}
}
}
The output of the above code is −
Folder: C:\Windows\System32\drivers Total Size: 156789023 bytes Total Size: 149.52 MB
Using Recursive Method for Better Control
For better error handling and progress tracking, you can implement a recursive method −
using System;
using System.IO;
class FolderSizeCalculator {
public static long CalculateFolderSize(string folderPath) {
long totalSize = 0;
try {
DirectoryInfo dir = new DirectoryInfo(folderPath);
// Add size of all files in current directory
foreach (FileInfo file in dir.GetFiles()) {
totalSize += file.Length;
}
// Recursively add size of all subdirectories
foreach (DirectoryInfo subDir in dir.GetDirectories()) {
totalSize += CalculateFolderSize(subDir.FullName);
}
} catch (UnauthorizedAccessException) {
Console.WriteLine($"Access denied: {folderPath}");
} catch (DirectoryNotFoundException) {
Console.WriteLine($"Directory not found: {folderPath}");
}
return totalSize;
}
public static void Main() {
string testFolder = @"C:\Users\Public\Documents";
long size = CalculateFolderSize(testFolder);
Console.WriteLine($"Folder: {testFolder}");
Console.WriteLine($"Size: {size} bytes");
Console.WriteLine($"Size: {size / 1024.0:F2} KB");
Console.WriteLine($"Size: {size / (1024 * 1024.0):F2} MB");
}
}
The output of the above code is −
Folder: C:\Users\Public\Documents Size: 2548736 bytes Size: 2488.03 KB Size: 2.43 MB
Formatted Size Display Method
Here's a complete example with a helper method to display sizes in human-readable format −
using System;
using System.IO;
using System.Linq;
class Program {
public static string FormatBytes(long bytes) {
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
order++;
len = len / 1024;
}
return $"{len:0.##} {sizes[order]}";
}
public static void Main() {
string[] testFolders = {
@"C:\Windows\Temp",
@"C:\Program Files\Common Files"
};
foreach (string folder in testFolders) {
try {
DirectoryInfo info = new DirectoryInfo(folder);
if (info.Exists) {
long size = info.EnumerateFiles("*", SearchOption.AllDirectories)
.Sum(file => file.Length);
int fileCount = info.EnumerateFiles("*", SearchOption.AllDirectories).Count();
Console.WriteLine($"Folder: {folder}");
Console.WriteLine($"Size: {FormatBytes(size)}");
Console.WriteLine($"Files: {fileCount}");
Console.WriteLine(new string('-', 40));
}
} catch (Exception ex) {
Console.WriteLine($"Error accessing {folder}: {ex.Message}");
Console.WriteLine(new string('-', 40));
}
}
}
}
The output of the above code is −
Folder: C:\Windows\Temp Size: 45.67 MB Files: 234 ---------------------------------------- Folder: C:\Program Files\Common Files Size: 1.23 GB Files: 5678 ----------------------------------------
Common Directory Operations
| Method | Description |
|---|---|
| EnumerateFiles() | Returns an enumerable collection of files in the current directory. |
| EnumerateDirectories() | Returns an enumerable collection of directory names in the current path. |
| GetFiles() | Returns an array of files in the current directory. |
| GetDirectories() | Returns an array of subdirectories in the current directory. |
| Exists | Gets a value indicating whether the directory exists. |
Conclusion
Calculating folder size in C# can be accomplished using DirectoryInfo.EnumerateFiles() with SearchOption.AllDirectories for a simple approach, or recursive methods for better error handling. Always include exception handling for access denied scenarios and non-existent directories.
