1

I use code like here Detecting USB drive insertion and removal using windows service and c# to detect when a USB device is plugged in / removed.

But when the user "ejects" the device leaving it plugged in I get no notification at all. Of course when I try to access such a drive it will fail.

Is there a different WMI Event I can use to get a notification about this situation?

The link @Jimi posted brings me a (BIG) step further.

public void AddWMIWatcher() {
WqlEventQuery query = new WqlEventQuery();
ManagementScope scope = new ManagementScope("root\\CIMV2");
query.EventClassName = "__InstanceOperationEvent";
query.WithinInterval = new TimeSpan(0, 0, 3);
query.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += Watcher_EventArrived;
watcher.Query = query;
watcher.Start();
}
private void Watcher_EventArrived(object sender, EventArrivedEventArgs e) {
ManagementBaseObject baseObject = e.NewEvent;

if(baseObject.ClassPath.ClassName.Equals("__InstanceCreationEvent")) {
    Console.WriteLine("A drive was connected");
}
else if(baseObject.ClassPath.ClassName.Equals("__InstanceDeletionEvent")) {
    Console.WriteLine("A drive was removed");
}
else if(baseObject.ClassPath.ClassName.Equals("__InstanceModificationEvent")) {
    Console.WriteLine("A drive was changed");
    //that is what I'm looking for
}

I get an __InstanceModificationEvent - the only thing I have to find out is how to get the affected drive (letter) out of this event.

ManniAT
  • 1,989
  • 2
  • 19
  • 25
  • Did you look at the answer by @AshkanMobayenKhiabani, which does notify of ejecting? Which answer did you actually copy? – Camilo Terevinto Oct 14 '18 at 14:01
  • 1
    [Give it a go](https://stackoverflow.com/questions/52598371/catch-usb-plug-and-unplug-event-system-invalidcastexception?answertab=active#tab-top). – Jimi Oct 14 '18 at 16:14
  • I tried "SELECT * FROM Win32_VolumeChangeEvent" but it doesn't work. – ManniAT Oct 14 '18 at 18:22
  • Well, just ask :) [Get serial number of usb storage device](https://stackoverflow.com/questions/49118708/get-serial-number-of-usb-storage-device-in-net-core-2-1?answertab=active#tab-top). (It doesn't get just the serial number). It's tagged `.net-core`, but it's the same thing. – Jimi Oct 14 '18 at 19:11
  • 1
    You may have noticed that `e.NewEvent.Properties["TargetInstance"].Value` can be cast to `ManagementBaseObject`. You can then take the `PNPDeviceID` property and use the code in the second link to extract the required informations: `SystemUSBDrives.USBDriveInfo CurrentDriveInfo = usbInfo.Where(uDev => uDev.PNPDeviceID == [CurrentManagementBaseObject].Properties["PNPDeviceID"].Value.ToString()).FirstOrDefault();`. See the usage sample code you find there. – Jimi Oct 14 '18 at 19:38

0 Answers0