如何在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是对表示驻留在盘驱动器上的盘分区的实例的引用。但我得到了未找到的异常
我该写些什么呢?
发布于 2016-12-24 07:40:32
这是我生成的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/中描述了此代码的计划
https://stackoverflow.com/questions/41307175
复制相似问题