如何在C#中查找驱动器的百分比
例如,如果C:驱动器有100GB空间,已使用25GB,则可用空间百分比应为75%。
例如,如果C:驱动器有100GB空间,已使用25GB,则可用空间百分比应为75%。
使用DriveInfo
类,如下所示:
DriveInfo drive = new DriveInfo("C");
double percentFree = 100 * (double)drive.TotalFreeSpace / drive.TotalSize;
如果你想获取任何UNC路径(可能是挂载到目录或共享的分区)上可用的免费空间,你需要调用Windows API。
class Program
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
static void Main(string[] args)
{
ulong available;
ulong total;
ulong free;
if (GetDiskFreeSpaceEx("C:\\", out available, out total, out free))
{
Console.Write("Total: {0}, Free: {1}\r\n", total, free);
Console.Write("% Free: {0:F2}\r\n", 100d * free / total);
}
else
{
Console.Write("Error getting free diskspace.");
}
// Wait for input so the app doesn't finish right away.
Console.ReadLine();
}
}
lpFreeBytesAvailable: 指向一个变量的指针,该变量接收与调用线程相关联的用户可用于磁盘上的总剩余字节数。 如果正在使用每个用户的配额,则该值可能小于磁盘上的总剩余字节数。
假设您所说的是免费的磁盘空间,而不是目录,请查看DriveInfo类。
您可以获取所有驱动器的信息:
DriveInfo[] drives = DriveInfo.GetDrives();
然后遍历数组,直到找到您感兴趣的驱动器:
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Free space on {0}: {1}", d.Name, d.TotalFreeSpace);
}