硬盘和驱动器列表

时间:2016-12-23 19:54:28

标签: c#

如何在c#中获取计算机上的硬盘及其分区(逻辑驱动器)列表? 我正在寻找能给我类似结果的代码

harddisk0:分区是C,D

harddisk1:分区是C,F,D

我试过这段代码

foreach (ManagementObject drive in search.Get())
{
   string antecedent = drive["DeviceID"].ToString(); 
   // the disk we're trying to find out about
   antecedent = antecedent.Replace(@"\", "\\"); 
   // this is just to escape the slashes
   string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" 
                     + antecedent 
                     + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
   using (ManagementObjectSearcher partitionSearch = new ManagementObjectSearcher(query))
      {
         foreach (ManagementObject part in partitionSearch.Get())
         {
            //...pull out the partition information
            Console.WriteLine("Dependent : {0}", part["Dependent"]);
          }
       }
}

知道dependent是对表示磁盘驱动器上的磁盘分区的实例的引用。 但我得到了未找到的例外

我应该写什么?

1 个答案:

答案 0 :(得分:1)

这是我生成的c#解决方案

    foreach (ManagementObject drive in search.Get())
            {

                string antecedent = drive["DeviceID"].ToString(); // the disk we're trying to find out about
                antecedent = antecedent.Replace(@"\", "\\"); // this is just to escape the slashes
                string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + antecedent + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
                using (ManagementObjectSearcher partitionSearch = new ManagementObjectSearcher(query))
                {
                    foreach (ManagementObject part in partitionSearch.Get())
                    {
                        //...pull out the partition information
                        MessageBox.Show(part["DeviceID"].ToString());
                        query = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + part["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition";
                        using (ManagementObjectSearcher logicalpartitionsearch = new ManagementObjectSearcher(query))
                            foreach (ManagementObject logicalpartition in logicalpartitionsearch.Get())
                            MessageBox.Show(logicalpartition["DeviceID"].ToString());
                    }

                }
            }

此脚本https://blogs.technet.microsoft.com/heyscriptingguy/2005/05/23/how-can-i-correlate-logical-drives-and-physical-disks/

中描述了此代码的计划