如何在c#中获得Total HardDrive并使用cpace?

时间:2014-09-09 05:20:07

标签: c# driveinfo

我有以下代码来获取单个驱动器的信息,但我想要整个硬盘信息.I.E。总大小和已用或可用空间

public List<DriveInformation> GetDriveInfo()
{
    List<DriveInformation> info = new List<DriveInformation>();
    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo drive in drives)
    {
        DriveInformation temp = new DriveInformation();
        temp.driveName = drive.Name;
        temp.driveSize = drive.TotalSize.ToString();
        temp.availableSize = drive.TotalFreeSpace.ToString();
        info.Add(temp);
    }
    return info;
}

如果我有一个未分配的驱动器,则驱动器信息无法显示该空间 例如:我有500GB硬盘,每个有2个(C&amp; D)分区200,然后这个功能只提供有关C和D的信息。我还想要未分配的空间细节(IEanother 100GB),无论是使用还是未分配。 / p>

1 个答案:

答案 0 :(得分:1)

试试这个。

    public static void GetDiskspace()
    {
        ConnectionOptions options = new ConnectionOptions();
        ManagementScope scope = new ManagementScope("\\\\localhost\\root\\cimv2",
        options);
        scope.Connect();
        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
        SelectQuery query1 = new SelectQuery("Select * from Win32_LogicalDisk");

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
        ManagementObjectCollection queryCollection = searcher.Get();
        ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
        ManagementObjectCollection queryCollection1 = searcher1.Get();

        foreach (ManagementObject m in queryCollection)
        {
            // Display the remote computer information

            Console.WriteLine("Computer Name : {0}", m["csname"]);
            Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]);
            Console.WriteLine("Operating System: {0}", m["Caption"]);
            Console.WriteLine("Version: {0}", m["Version"]);
            Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
            Console.WriteLine();
        }

        foreach (ManagementObject mo in queryCollection1)
        {
            // Display Logical Disks information

            Console.WriteLine("              Disk Name : {0}", mo["Name"]);
            Console.WriteLine("              Disk Size : {0}", mo["Size"]);
            Console.WriteLine("              FreeSpace : {0}", mo["FreeSpace"]);
            Console.WriteLine("          Disk DeviceID : {0}", mo["DeviceID"]);
            Console.WriteLine("        Disk VolumeName : {0}", mo["VolumeName"]);
            Console.WriteLine("        Disk SystemName : {0}", mo["SystemName"]);
            Console.WriteLine("Disk VolumeSerialNumber : {0}", mo["VolumeSerialNumber"]);
            Console.WriteLine();
        }
        string line;
        line = Console.ReadLine();
    }