I've always used the method of overriding WndProc(ref Message m) to get events for drive inserted/removed and created my own eventarg to return the drive letter. This worked perfectly but now I'm busy developing a service project and obviously cannot use the above-mentioned method.
I'm using now WMI:
//insert
WqlEventQuery creationQuery = new WqlEventQuery();
creationQuery.EventClassName = "__InstanceCreationEvent";
creationQuery.WithinInterval = new TimeSpan(0, 0, 2);
creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
ManagementEventWatcher creationWatcher = new ManagementEventWatcher(creationQuery);
creationWatcher.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
creationWatcher.Start();
This correctly lets the event fire when a USB flash is plugged in. Now what I need help with is how to get the drive letter (eg E:) from the event?
Here is what I have played around in my event so far:
internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
{
EventLog.WriteEntry("USB PLUGGED IN!");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
EventLog.WriteEntry(property.Name + " = " + property.Value);
}
}
I can't get the drive letter from "Properties". Is there a way to get the drive letter? Or do I need to look at the problem from a completely different angle?