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.