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:

 public double totalSize = 0;  
 private void btnCalculate_Click(object sender, EventArgs e)  
 {  
    GetTotalSize("ENTER YOUR FOLDER PATH HERE");  
 }      

 public void GetFileSize(string path)  
 {  
    FileInfo fi = new FileInfo(path);  
    totalSize += fi.Length;  
 }  

 public void GetTotalSize(string directory)  
 {  
    string[] files = Directory.GetFiles(directory);  
    foreach (string file in files)  
    {  
        GetFileSize(file);  
    }  

    string[] subDirs = Directory.GetDirectories(directory);  
    foreach (string dir in subDirs)  
    {  
        GetTotalSize(dir);  
    }  

    double size= totalSize / Math.Pow(1024, 2);  
    MessageBox.Show(Convert.ToString(size));  
 }  

No comments:

Post a Comment