Friday, July 30, 2010

How to find folder/direcotry size - C#

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(FindFolderSize(new DirectoryInfo(Server.MapPath("~")), UnitType.KB, 0).ToString() + " KB");
    Response.Write("<br />");
    Response.Write(FindFolderSize(new DirectoryInfo(Server.MapPath("~")), UnitType.MB, 2).ToString() + " MB");
    Response.Write("<br />");
    Response.Write(FindFolderSize(new DirectoryInfo(Server.MapPath("~")), UnitType.GB, 5).ToString() + " GB");
}
 
public enum UnitType { KB = 1, MB = 2, GB = 3 }
/// <summary>
/// Find foler size
/// </summary>
/// <param name="d">Target folder</param>
/// <param name="u">Unit type [KB, MB, GB]</param>
/// <param name="r">Number to digits to round up</param>
/// <returns></returns>
public double FindFolderSize(DirectoryInfo d, UnitType u, int r)
{
    double divider = Math.Pow(1024, (int)u);
    double size = 0;
    foreach (FileInfo f in d.GetFiles())
        size += Convert.ToDouble(f.Length) / divider;
    foreach (DirectoryInfo c in d.GetDirectories())
        size += this.FindFolderSize(c, u, r);
    return Math.Round(size, r);
}

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...