从 DeviceNotifyEventArgs 获取 usb 字母

Get usb letter from DeviceNotifyEventArgs

我找不到如何提取插入的USB盘符。

我有监听插入的usb的事件,但是我需要插入的字母,因为我有多个usb端口。

void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
{
  MessageBox.Show(e.ToString());
}

打印:

[DeviceType:DeviceInterface] [EventType:DeviceArrival] FullName:USB#VID_2CE3&PID_6487#0000000000000000#{a5dcbf10-6530-11d2-901f-00c04fb951ed} Vid:0x2CE3 Pid:0x6487 SerialNumber:0000000000000000 ClassGuid:a5dcbf10-6530-11d2-901f-00c04fb951ed

我正在使用 LibUsbDotNet.DeviceNotify dll

例如:E:\插入

由于 DeviceNotifyEventArgs 包含序列号,您可以在 WMI 的帮助下使用它来查找设备号。

这里是 this answer 的改编版本:

// enumerate usb drives
foreach (var drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
    // find driver with known serial number
    if ((string)drive.Properties["SerialNumber"].Value == serialNumber)
        // associate partitions with drive
        foreach (var partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
            // associate logical disk with partition
            foreach (var disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
                Console.WriteLine("Disk=" + disk["Name"]);

确保将所有内容都包装到 using 中:需要处理 Get() 返回的所有搜索器和集合。