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.
Step 1 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("/Users/sam/programs");
Console.WriteLine(size);
}
static long GetDirectorySize(string p)
{
// Get array of all file names.
string[] a = Directory.GetFiles(p, "*.*");
// Calculate total bytes of all files in a loop.
long b = 0;
foreach (string name in a)
{
// Use FileInfo to get length of each file.
FileInfo info = new FileInfo(name);
b += info.Length;
}
// Return total size
return b;
}
}382627
All directories. To get files in nested folders, use the SearchOption.AllDirectories argument. This returns an array with files from subdirectories.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 19, 2023 (edit).