How can I get the total size of a particular folder in C#?
💻 coding

How can I get the total size of a particular folder in C#?

1 min read 234 words
1 min read
ShareWhatsAppPost on X
  • 1To calculate the total size of a folder in C#, use a function that iterates through all files and sums their sizes.
  • 2The provided code includes a method to convert byte counts into human-readable formats like KB, MB, and GB.
  • 3You can calculate the percentage of used space by comparing the total bytes used to a predefined maximum space limit.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"To calculate the total size of a folder in C#, use a function that iterates through all files and sums their sizes."

How can I get the total size of a particular folder in C#?

When I'm creating one application where I'm giving certain memory space to users and I want to calculate the total space he used in his folder and to show him/her the total space utilized and total remaining space that can be utilized. How can I calculate the size of the entire folder including all files of a particular folder in c#?

Solution:

You can use the following function to calculate the size of a specific folder.

static String GetDriveSize(String ParticularFolder, String drive)
 {
 String size = "";
 long MaxSpace = 10485760;
 String rootfoldersize = @"~/userspace/" + ParticularFolder+ "/";
 long totalbytes = 0;
 long percentageusage = 0;

 totalbytes = GetFolderSize(System.Web.HttpContext.Current.Server.MapPath(rootfoldersize) + "" + drive + "/");
 percentageusage = (totalbytes * 100) / MaxSpace;
 size = BytesToString(totalbytes);

 return size;
 }

static long GetFolderSize(string s)
 {
 string[] fileNames = Directory.GetFiles(s, "*.*");
 long size = 0;

 // Calculate total size by looping through files in the folder and totalling their sizes
 foreach (string name in fileNames)
 {
 // length of each file.
 FileInfo details = new FileInfo(name);
 size += details.Length;
 }
 return size;
 }

static String BytesToString(long byteCount)
 {
 string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
 if (byteCount == 0)
 return "0" + suf[0];
 long bytes = Math.Abs(byteCount);
 int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
 double num = Math.Round(bytes / Math.Pow(1024, place), 1);
 return (Math.Sign(byteCount) * num).ToString() + suf[place];
 }

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 25 October 2018 · 1 min read · 234 words

Part of AskGif Blog · coding

You might also like

How can I get the total size of a particular folder in C#? | AskGif Blog