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

准备

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

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

正文

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

/// 
/// Retrieves information about the specified disk, including the amount of free space on the disk.
/// 获取指定磁盘的信息,包括磁盘的可用空间。
///

/// 磁盘根目录。如:"C:\\"
/// 每个簇所包含的扇区个数
/// 每个扇区所占的字节数
/// 空闲的簇的个数
/// 簇的总个数
///
[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.大功告成。

转载于:https://www.cnblogs.com/ainijiutian/archive/2010/01/06/1640760.html

你可能感兴趣的:(查看文件夹大小及占用空间)