【问题标题】:List Of Hard Disks and drives on them硬盘及其上的驱动器列表
【发布时间】:2016-12-23 19:54:28
【问题描述】:

如何在 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"]);
          }
       }
}

知道从属是对表示驻留在磁盘驱动器上的磁盘分区的实例的引用。 但是我得到了 Not Found 的异常

请问我应该写什么?

【问题讨论】:

标签: c#


【解决方案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/

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2011-09-03
    • 1970-01-01
    • 2017-02-21
    • 2012-02-08
    • 1970-01-01
    • 2010-09-09
    • 2010-12-12
    相关资源
    最近更新 更多