Tuesday, May 7, 2013

Get the total size of a folder using CSharp (C#)


When the user clicks the btnCalculate button, the size of the each file inside the folder is calculated by looping through the folder.
C# Code:

  1. public double totalSize = 0;
  2. private void btnCalculate_Click(object sender, EventArgs e)
  3. {
  4. GetTotalSize("ENTER YOUR FOLDER PATH HERE");
  5. }
  6.  
  7. public void GetFileSize(string path)
  8. {
  9. FileInfo fi = new FileInfo(path);
  10. totalSize += fi.Length;
  11. }
  12.  
  13. public void GetTotalSize(string directory)
  14. {
  15. string[] files = Directory.GetFiles(directory);
  16. foreach (string file in files)
  17. {
  18. GetFileSize(file);
  19. }
  20.  
  21. string[] subDirs = Directory.GetDirectories(directory);
  22. foreach (string dir in subDirs)
  23. {
  24. GetTotalSize(dir);
  25. }
  26.  
  27. double size= totalSize / Math.Pow(1024, 2);
  28. MessageBox.Show(Convert.ToString(size));
  29. }

No comments:

Post a Comment