首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >硬盘和硬盘上的驱动器列表

硬盘和硬盘上的驱动器列表
EN

Stack Overflow用户
提问于 2016-12-24 03:54:28
回答 1查看 696关注 0票数 1

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

Harddisk0:分区为C、D

Harddisk1:分区为C、F、D

我已经试过这个代码了

代码语言:javascript
运行
复制
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是对表示驻留在盘驱动器上的盘分区的实例的引用。但我得到了未找到的异常

我该写些什么呢?

EN

回答 1

Stack Overflow用户

发布于 2016-12-24 07:40:32

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

代码语言:javascript
运行
复制
    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/中描述了此代码的计划

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41307175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档