获取逻辑驱动器列表

Pau*_*ulB 40 c# hard-drive

如何获取系统上的逻辑驱动器(C#)列表以及它们的容量和可用空间?

Chr*_*nce 29

foreach (var drive in DriveInfo.GetDrives())
{
    double freeSpace = drive.TotalFreeSpace;
    double totalSpace = drive.TotalSize;
    double percentFree = (freeSpace / totalSpace) * 100;
    float num = (float)percentFree;

    Console.WriteLine("Drive:{0} With {1} % free", drive.Name, num);
    Console.WriteLine("Space Remaining:{0}", drive.AvailableFreeSpace);
    Console.WriteLine("Percent Free Space:{0}", percentFree);
    Console.WriteLine("Space used:{0}", drive.TotalSize);
    Console.WriteLine("Type: {0}", drive.DriveType);
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*ter 22

Directory.GetLogicalDrives

他们的例子更加强大,但这就是它的关键所在

string[] drives = System.IO.Directory.GetLogicalDrives();

foreach (string str in drives) 
{
    System.Console.WriteLine(str);
}
Run Code Online (Sandbox Code Playgroud)

您还可以P/Invoke并调用win32函数(如果您使用的是非托管代码,则使用它).

但是只获得驱动器列表,有关每个驱动器的信息,您可能希望使用GetDrives作为Chris Ballance演示.


小智 6

也许这就是你想要的:

listBox1.Items.Clear();

foreach (DriveInfo f in DriveInfo.GetDrives())    
    listBox1.Items.Add(f);
Run Code Online (Sandbox Code Playgroud)