Home
Search
C# Get Directory SizeUse the Length property on FileInfo to compute the total size of a directory in bytes.
Directory size. A C# method can calculate the total size of a directory. It considers each file. It returns the total bytes of all files.
Some uses. This C# method is useful for compression or file transfers. We determine the size of a directory. We can detect changes in directory sizes.
Directory.GetFiles
Directory
File
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.
Array
Step 2 The prorgram loops over each file. The foreach-loop looks through each file name and then creates a new FileInfo object.
FileInfo This object allows us to easily find certain informational properties of the file.
FileInfo
Finally It returns the sum of all the bytes in the first level of the folder. This value is stored in the long type.
Long
C# program that gets directory size
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.
Recursive File List
Note Thanks to Joe for suggesting this option. It makes GetDirectorySize more powerful, but is not always needed.
Also You can also modify the method to return only the sizes of files of a specific type (like PNG).
Possible arguments to GetFiles:
SearchOption.AllDirectories "*.*" "*.png"
A summary. We measured directory sizes in bytes. We can use a combination of Directory methods and FileInfo objects to sum the bytes.
Home
© 2007-2021 sam allen. see site info on the changelog