• 查看文件夹大小及占用空间


    准备

      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.大功告成。

  • 相关阅读:
    公用表表达式(CTE)的递归调用
    c# 如何让tooltip显示文字换行
    实战 SQL Server 2008 数据库误删除数据的恢复
    SQL SERVER数据库中 是否可以对视图进行修改删除
    asp.net中实现文件批量上传
    sql server 2008学习2 文件和文件组
    sql server 2008学习3 表组织和索引组织
    sql server 2008学习4 设计索引的建议
    sql server 2008学习10 存储过程
    .net 调用 sql server 自定义函数,并输出返回值
  • 原文地址:https://www.cnblogs.com/ainijiutian/p/1640760.html
Copyright © 2020-2023  润新知