How to calculate the Size of Folder using C#?


To calculate the size of a folder in C#, use the Directory.EnumerateFiles Method and get the files.

To get the sub- directories, use the EnumerateDirectories method. Our folder is set using DirectoryInfo class −

DirectoryInfo info = new DirectoryInfo(@"D:/new");

Now find the size −

long totalSize = info.EnumerateFiles().Sum(file => file.Length);

For the directories, use −

info.EnumerateDirectories()

Other manipulations you can perform on Directories in C# are:

MethodDescription
CreateDirectory(String)Creates all directories and subdirectories in the specified path unless they already exist.
CreateDirectory (String, DirectorySecurity)Creates all the directories in the specified path, unless the already exist, applying the specified Windows security.
Delete(String)Deletes an empty directory from a specified path.
Delete(String, Boolean)Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
EnumerateDirectories(String)Returns an enumerable collection of directory names in a specified path.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements