这种类型的枚举通常使用System.Management
's
管理对象搜索器 https://learn.microsoft.com/en-us/dotnet/api/system.management.managementobjectsearcher使用 WQL 构建查询协会会员 https://learn.microsoft.com/en-us/windows/win32/wmisdk/associators-of-statement陈述
这是您可以遵循的一种顺序路径来检索系统中驱动器的信息:
枚举磁盘驱动器 => 对于每个 [DeviceID] =>
枚举要分区的磁盘驱动器 => 对于每个 [DeviceID]
枚举逻辑磁盘到分区
每个类中的对象都有其关联的属性:
磁盘驱动器 (MSDN) https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-diskdrive
分区(MSDN) https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-logicaldisktopartition
逻辑磁盘 (MSDN) https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-logicaldisk
using System.Management;
//Define an initial scope for the following queries
var scope = new ManagementScope(@"\\" + Environment.MachineName + @"\root\CIMV2");
//Select all Disk Drives
var query = new SelectQuery("SELECT * FROM Win32_DiskDrive");
//Options => Timeout infinite to avoid timeouts and forward only for speed
var options = new EnumerationOptions();
options.Timeout = EnumerationOptions.InfiniteTimeout;
options.Rewindable = false;
options.ReturnImmediately = true;
//New root Management Object
var searcher = new ManagementObjectSearcher(scope, query, options);
//Enumerate all Disk Drives
foreach (ManagementObject moDisk in searcher.Get())
{
//Query the associated partitions of the current DeviceID
string assocQuery = "Associators of {Win32_DiskDrive.DeviceID='" +
mobDisk.Properties["DeviceID"].Value.ToString() + "'}" +
"where AssocClass=Win32_DiskDriveToDiskPartition";
var assocPart = new ManagementObjectSearcher(assocQuery);
assocPart.Options.Timeout = EnumerationOptions.InfiniteTimeout;
//For each Disk Drive, query the associated partitions
foreach (ManagementObject moPart in assocPart.Get())
{
Console.WriteLine("DeviceID: {0} BootPartition: {1}",
moPart.Properties["DeviceID"].Value.ToString(),
moPart.Properties["BootPartition"].Value.ToString());
//Query the associated logical disk of the current PartitionID
string logDiskQuery = "Associators of {Win32_DiskPartition.DeviceID='" +
moPart.Properties["DeviceID"].Value.ToString() + "'} " +
"where AssocClass=Win32_LogicalDiskToPartition";
var logDisk = new ManagementObjectSearcher(logDiskQuery);
logDisk.Options.Timeout = EnumerationOptions.InfiniteTimeout;
//For each partition, query the Logical Drives
foreach (var logDiskEnu in logDisk.Get())
{
Console.WriteLine("Volume Name: {0} Serial Number: {1} System Name: {2}",
logDiskEnu.Properties["VolumeName"].Value.ToString(),
logDiskEnu.Properties["VolumeSerialNumber"].Value.ToString(),
logDiskEnu.Properties["SystemName"].Value.ToString());
Console.WriteLine("Description: {0} DriveType: {1} MediaType: {2}",
logDiskEnu.Properties["Description"].Value.ToString(),
logDiskEnu.Properties["DriveType"].Value.ToString(),
logDiskEnu.Properties["MediaType"].Value.ToString());
}
}
}