且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 WMI 获取 USB 设备的驱动器号

更新时间:2022-03-15 02:35:17

您收到一个异常,因为您的 deviceID 包含需要转义的字符(反斜杠).使用简单的替换,您不应该得到异常.

You get an exception because your deviceID contains characters that need to be escaped (backslashes). With simple replace you shouldn't get the exception.

string query = string.Format("SELECT * FROM Win32_LogicalDisk WHERE DeviceID='{0}'", deviceID.Replace(@"\", @"\\"));

但是,从 WMI 获取 USB 驱动器盘符要复杂一些.您需要学习一些课程,如@MSalters 在评论中发布的链接所述:

However, getting USB drive letter from WMI is a little more complicated. You need to go through a few classes, as stated in a link that @MSalters posted in his comment:

Win32_DiskDrive-> Win32_DiskDriveToDiskPartition -> Win32_DiskPartition -> Win32_LogicalDiskToPartition -> Win32_LogicalDisk.

此处为我工作:

foreach (ManagementObject device in new ManagementObjectSearcher(@"SELECT * FROM Win32_DiskDrive WHERE InterfaceType LIKE 'USB%'").Get())
{
    Console.WriteLine((string)device.GetPropertyValue("DeviceID"));
    Console.WriteLine((string)device.GetPropertyValue("PNPDeviceID"));                

    foreach (ManagementObject partition in new ManagementObjectSearcher(
        "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + device.Properties["DeviceID"].Value
        + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
    {
        foreach (ManagementObject disk in new ManagementObjectSearcher(
                    "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='"
                        + partition["DeviceID"]
                        + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
        {
            Console.WriteLine("Drive letter " + disk["Name"]);
        }
    }
}