zoukankan      html  css  js  c++  java
  • 查看文件夹大小及占用空间

    准备

      1.簇:要了解文件的大小及占用空间的含义,必须先了解簇的定义。相关信息请看这里

      2.GetDiskFreeSpace:获取指定磁盘的信息,包括磁盘的可用空间(Retrieves information about the specified disk, including the amount of free space on the disk)。参考这里。此方法来自 kernel32.dll。具体调用请看正文。

    正文

      1.调用GetDiskFreeSpace获取磁盘信息。

    /// <summary>
    /// Retrieves information about the specified disk, including the amount of free space on the disk.
    /// 获取指定磁盘的信息,包括磁盘的可用空间。
    /// </summary>
    /// <param name="lpRootPathName">磁盘根目录。如:"C:\\"</param>
    /// <param name="lpSectorsPerCluster">每个簇所包含的扇区个数</param>
    /// <param name="lpBytesPerSector">每个扇区所占的字节数</param>
    /// <param name="lpNumberOfFreeClusters">空闲的簇的个数</param>
    /// <param name="lpTotalNumberOfClusters">簇的总个数</param>
    /// <returns></returns>
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool GetDiskFreeSpace(string lpRootPathName,
    out uint lpSectorsPerCluster,
    out uint lpBytesPerSector,
    out uint lpNumberOfFreeClusters,
    out uint lpTotalNumberOfClusters);

      2.获取指定磁盘的簇大小。

    public int BytesPerCluster(string drive)
    {
    uint lpSectorsPerCluster;
    uint lpBytesPerSector;
    uint lpNumberOfFreeClusters;
    uint lpTotalNumberOfClusters;
    GetDiskFreeSpace(drive,
    out lpSectorsPerCluster,
    out lpBytesPerSector,
    out lpNumberOfFreeClusters,
    out lpTotalNumberOfClusters);
    return (int)(lpBytesPerSector * lpSectorsPerCluster);
    }

      3.获取文件夹大小及占用空间。

    public void DirectoryProperities(string path, int bytesPerCluster, ref long size, ref long usage)
    {
    long temp;
    FileInfo fi = null;
    foreach (string file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
    {
    fi = new FileInfo(file);
    temp = fi.Length;
    size += temp;
    usage += temp + (temp % bytesPerCluster == 0 ? 0 : bytesPerCluster - temp % bytesPerCluster);
    }
    }

      4.剩下的就是除法运算了。

    private void Form1_Load(object sender, EventArgs e)
    {
    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
    {
    string path = folderBrowserDialog1.SelectedPath;
    long size = 0, usage = 0;
    DirectoryProperities(path, BytesPerCluster(Path.GetPathRoot(path)), ref size, ref usage);
    lblSize.Text = ((double)size / 1024 / 1024).ToString("0.00 MB")
    + "(" + size.ToString("N0") + " 字节)";
    lblUsage.Text = ((double)(usage >> 10) / 1024).ToString("0.00 MB")
    + "(" + usage.ToString("N0") + " 字节)";
    }
    }

      5.大功告成。

  • 相关阅读:
    WCF 第二章 契约 异步访问服务操作
    WCF 第一章 基础 在IIS中寄宿服务
    哈希表 解释 和 实现
    ACM2010省赛总结
    hashTable实现
    c# winform 应用编程代码总结 14
    徽文化让世博更多彩
    c# winform 应用编程代码总结 15
    Socket用法详解
    IE插件技术 BHO C# IE 插件
  • 原文地址:https://www.cnblogs.com/ainijiutian/p/1640760.html
Copyright © 2011-2022 走看看