C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Step 1: The program calls Directory.GetFiles(). This gets all the files matching the "filter" at the directory in the path specified.
StaticArrayStep 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.
FileInfoFinally: It returns the sum of all the bytes in the first level of the folder. This value is stored in the long type.
LongC# 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;
}
}
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);
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");
Tip: This site contains a useful tutorial on the FolderBrowserDialog control, which can help with getting this working.
FolderBrowserDialogDialogResultCode 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);
}