TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Get Directory Size

This C# article shows how to use the Length property on FileInfo. It computes the size of a directory.

Directory size. A method can calculate the total size of a directory.

It considers each file. It returns the total bytes of all files. This is useful for compression or file transfers. We determine the size of a directory.

Example. We can use the Directory class and a foreach-loop. The .NET Framework does not provide one method to determine the directory size. We must write our own custom method. Here we sum the length of each file, returning the total size in bytes.

C# program that gets directory size

using System;
using System.IO;

class Program
{
    static void Main()
    {
	Console.WriteLine(GetDirectorySize("C:\\Site\\"));
    }

    static long GetDirectorySize(string p)
    {
	// 1.
	// Get array of all file names.
	string[] a = Directory.GetFiles(p, "*.*");

	// 2.
	// Calculate total bytes of all files in a loop.
	long b = 0;
	foreach (string name in a)
	{
	    // 3.
	    // Use FileInfo to get length of each file.
	    FileInfo info = new FileInfo(name);
	    b += info.Length;
	}
	// 4.
	// Return total size
	return b;
    }
}

This method is static. It doesn't save any state information. In step 1, it calls Directory.GetFiles(). This gets all the files matching the "filter" at the directory in the path specified. It fills a string array with all the file names.

Static MethodString Array

 

Next, it loops over each file. The foreach-loop looks through each file name and then creates a new FileInfo object. 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

All directories. The previous method gets only the files in the specified folder. It does not get files in sub-folders. 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.

Statement that gets files: C#

// 1.
// Get array of all file names.
string[] a = Directory.GetFiles(p, "*.*");

Statement that gets files recursively: C#

// 1.
// Recursively scan directories.
string[] a = Directory.GetFiles(p, "*.*", SearchOption.AllDirectories);

File types. You can also modify the method to return only the sizes of files of a specific type. For example, you can get just the sizes of PNG files in a folder. Here are the statements to modify.

Directory.GetFiles

Also: This can be combined with the SearchOption.AllDirectories enum for even more control.

Statement that gets all files: C#

// 1.
// Get array of all file names.
string[] a = Directory.GetFiles(p, "*.*");

Statement that gets PNG files: C#

// 1.
// Get array of PNG files.
string[] a = Directory.GetFiles(p, "*.png");

FolderBrowserDialog. You can use this method with the FolderBrowserDialog control in Windows Forms. Use the path returned from the dialog, after DialogResult.OK, and pass it to the method above. The following Windows Forms example shows how this is done.

Tip: This site contains a useful tutorial on the FolderBrowserDialog control, which can help with getting this working.

FolderBrowserDialogDialogResult

Code fragment: C#

// Show the folder browser.
DialogResult result = folderBrowserDialog1.ShowDialog();

if (result == DialogResult.OK)
{
    // Path specified.
    string folder = folderBrowserDialog1.SelectedPath;

    // Calculate total size of all pngs.
    long directorySize = GetDirectorySize(folder);
}

Summary. We measured directory sizes in bytes. We can use a combination of Directory methods and FileInfo objects to sum the bytes. You can also use this method with a FolderBrowserDialog or other UI in Windows Forms.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf