Morpheusweb.it - Risorse per webmaster: script, ASP.NET, C#, Visual Basic .Net, tutorial, asp, javascript, css, php, html, java, ADO, VBScript, forms, frames, Active Server Pages, Dynamic HTML, database, gratis per webmaster e webdesigner


Calculate the size of a Directory


<%@ Page language="c#" %>
<%@ Import Namespace="System.IO" %>
<HTML>
<script language="c#" runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
  string strFolderPath = "./Upload";
  DirectorySize clsDirectorySize = new DirectorySize();
  lbDimensioneCartella.Text = "Folder size: " +
  clsDirectorySize.Size(strFolderPath);
}

public class DirectorySize : System.Web.UI.Page
{
  public string Size(string virtualPath)
  {
    if (virtualPath == "")
      virtualPath = "/";
    else if (virtualPath.EndsWith("/"))
      virtualPath = virtualPath.Substring(0, virtualPath.Length - 1);
    string physicalPath = Server.MapPath(virtualPath);
    double folderSize = GetFolderSize(physicalPath);
    string strSize = FormatSize(folderSize);
    return strSize;
  }

  private double GetFolderSize(string physicalPath)
  {
    double dblDirSize = 0;
    DirectoryInfo objDirInfo = new DirectoryInfo(physicalPath);
    Array arrChildFiles = objDirInfo.GetFiles();
    Array arrSubFolders = objDirInfo.GetDirectories();
    foreach (FileInfo objChildFile in arrChildFiles)
    {
      dblDirSize += objChildFile.Length;
    }
    foreach (FileInfo objChildFolder in arrSubFolders)
    {
      dblDirSize += GetFolderSize(objChildFolder.FullName);
    }
    return dblDirSize;
  }

  private string FormatSize(double dblFileSize)
  {
    if (dblFileSize < 1024)
      return String.Format("{0:N0} B", dblFileSize);
    else if (dblFileSize < 1024 * 1024)
      return String.Format("{0:N2} KB", dblFileSize / 1024);
    else if (dblFileSize < 1024 * 1024 * 1024)
      return String.Format("{0:N2} MB", dblFileSize / (1024 * 1024));
    else if (dblFileSize >= 1024 * 1024 * 1024)
      return "Dimensione in GB!";
  }
}
</script>
<body>
<asp:Label ID="lbDimensioneCartella" runat="server"></asp:Label>
</body>
</HTML>



Download Code...


Print Page


 


Page top

risorse per webmaster