0

I'd like to get the Drive-Letter from the new plugged USB-Media(such as, HardDisks, USBSticks, CD-Cards ect.)

Please Note: I want only the new plugged. Not the existing ones.

For Example1: User plugs in a USB-Stick. The Method should return: "F:"

For Example2: User plugs in a External HDD with two Partition. The Method should return: "G:" and "H:"

I have the following code: But it just trigger the insert. Not the Drive-Letter.

public void TrigerUSBInsert()
{
    try
    {
        WqlEventQuery w = new WqlEventQuery
        {
            EventClassName = "__InstanceCreationEvent",
            Condition = "TargetInstance ISA 'Win32_USBControllerDevice'",
            WithinInterval = new TimeSpan(0, 0, 2)
        };

        ManagementEventWatcher watch = new ManagementEventWatcher(w);
        watch.EventArrived += new EventArrivedEventHandler(this.usbDetectionHandler);
        watch.Start();
    }
    catch (Exception exception)
    {

    }
}

Thank you.

  • http://social.msdn.microsoft.com/Forums/en-US/d2ad33a7-dd5f-42ed-bd55-c5b4102f7ba7/detection-usb-device-and-get-drive-letter?forum=csharplanguage – George Duckett Jul 17 '14 at 14:25

1 Answers1

0

Try using Win32_LogicalDisk instead of Win32_USBControllerDevice.

This will trigger as soon as a Win32_LogicalDisk is created, which happens when you insert a usb drive. It also happens when you install any other disk drive, like S-ATA HDDs, but those aren't installed during runtime most of the time (bar hot-plug systems, of course).

Edit:

Oh, I forgot: You'll need to get the ManagementObject via:

ManagementBaseObject o = (ManagementBaseObject) args.NewEvent.Properties["TargetInstance"].Value;

With that you can iterate through its properties:

foreach (PropertyData pd in o.Properties)
{
   Console.WriteLine("{0}: \t {1}", pd.Name, pd.Value);
}

One of its properties is the drive letter.

(For a list of its properties and available Win32_ classes see here: http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx

wickermoon
  • 171
  • 1
  • 10