如何在c#中找到驱动器的可用百分比

时间:2010-06-06 14:54:29

标签: c#

如何在c#

中找到驱动器的百分比

例如

如果c:为100 gb且使用的空间为25 gb,则游离百分比应为75%

4 个答案:

答案 0 :(得分:11)

使用DriveInfo class,如下所示:

DriveInfo drive = new DriveInfo("C");
double percentFree = 100 * (double)drive.TotalFreeSpace / drive.TotalSize;

答案 1 :(得分:5)

如果要获取任何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:   指向接收总空闲数的变量的指针   磁盘上可用的字节数   与之关联的用户   调用线程。   如果正在使用每用户配额,则此值可能小于总数   磁盘上的空闲字节数。

答案 2 :(得分:1)

假设您正在讨论免费的驱动器空间,而不是目录,请查看DriveInfo类。

您可以获取所有驱动器的信息:

DriveInfo[] drives = DriveInfo.GetDrives();

然后迭代数组,直到找到您感兴趣的驱动器:

foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Free space on {0}: {1}", d.Name, d.TotalFreeSpace);
}

答案 3 :(得分:0)

我认为你指的是分区。如果是这种情况,this应该有所帮助。

相关问题