1

I can't find how to extract the inserted usb letter.

I have event that listen to usb that inserted, but I need the inserted letter, because I have mulpile usb ports.

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

Prints:

[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

I'm using LibUsbDotNet.DeviceNotify dll

For example: E:\ inserted

Codey
  • 487
  • 1
  • 8
  • 27
  • 1
    What is usb letter? You mean letter of usb-drive? – Sinatr Apr 01 '19 at 14:26
  • 1
    Possible duplicate of [How to find USB drive letter?](https://stackoverflow.com/questions/123927/how-to-find-usb-drive-letter) – Sinatr Apr 01 '19 at 14:28
  • @Sinatr That's not the same, because I want to get the letter from the event parameter – Codey Apr 01 '19 at 14:33
  • This event is generic event for usb devices, not usb drives. It provides you with no such info. But you can use some property (VID+PID? serial number? classguid?) to find that device using WMI and get its letter using [this answer](https://stackoverflow.com/a/124025/1997232). – Sinatr Apr 01 '19 at 14:37
  • @Sinatr If you can then please post a code snippt as answer – Codey Apr 01 '19 at 14:41

1 Answers1

0

Since DeviceNotifyEventArgs contains serial number you can use it to find device letter with help of WMI.

Here is adapted version of 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"]);

Make sure to wrap everything into using: all searchers and collection returned by Get() needs to be disposed.

Sinatr
  • 20,892
  • 15
  • 90
  • 319