Example. We can use the Directory class and a foreach-loop. We write our own custom method—we sum the length of each file, returning the total size in bytes.
Start The program calls Directory.GetFiles(). This gets all the files matching the "filter" at the directory in the path specified.
using System;
using System.IO;
class Program
{
static void Main()
{
var size = GetDirectorySize(@"programs\");
Console.WriteLine(size);
}
static long GetDirectorySize(string path)
{
// Get array of all file names.
string[] files = Directory.GetFiles(path, "*.*");
// Calculate total bytes of all files in a loop.
long totalBytes = 0;
foreach (string name in files)
{
// Use FileInfo to get length of each file.
FileInfo info = new FileInfo(name);
totalBytes += info.Length;
}
// Return total size
return totalBytes;
}
}382627
All directories. To get files in nested folders, use the SearchOption.AllDirectories argument. This returns an array with files from subdirectories.
Info You can modify the method to return only the sizes of files of a specific type (like PNG).
SearchOption.AllDirectories
"*.*""*.png"
Summary. We measured directory sizes in bytes. We can use a combination of Directory methods and FileInfo objects to sum the bytes.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.