How to calculate / determine folder size in .NET?

I am creating an application in Winform, which, among other things, should also be able to calculate the size of the folder.

Can someone give me pointers on how to do this?

thanks

+4
source share
3 answers

To do this, I use the following extension method:

public static long Size(this DirectoryInfo Directory, bool Recursive = false) { if (Directory == null) throw new ArgumentNullException("Directory"); return Directory.EnumerateFiles("*", Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Sum(x => x.Length); } 
+15
source

You will need to recursively list the files in the folder and summarize the file sizes. Remember to include system and hidden files for the correct size.

Here is a simple version:

 long GetFolderSize(string path) { DirectoryInfo d = new DirectoryInfo(path); var files = d.GetFiles("*", SearchOption.AllDirectories); return files.Sum(fi => fi.Length); } 

Remember that a file can take up more disk space than its length, because the file always takes up integer numbers of blocks in the file system (in case it matters to your application).

+2
source

You need to get all the files from your directory (including subdirectories) and their size in total. Example:

 static long GetDirectorySize(string path) { string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); long size = 0; foreach (string name in files) { FileInfo info = new FileInfo(name); size += info.Length; } return size; } 
+2
source

All Articles