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:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...