How can I get a device Id and other description on insertion of USB device?
I've found an example how to get notified about USB device insertion/removal. But how to get device desrtiption info?
Here is my code snippet:
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(USBRemoved);
w.Start();
}
... catch()....
UPDATE: Actually, it is a Serial COM device with USB connection. So there is no driveName property. How can I get USB description, which I can see in Device Manager? Does WMI provide this info with the notification about USB insertion?
Complete new answer according to your updated answer. You may check für any connected USB device:
ManagementScope sc =
new ManagementScope(@"\\YOURCOMPUTERNAME\root\cimv2");
ObjectQuery query =
new ObjectQuery("Select * from Win32_USBHub");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
ManagementObjectCollection result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["Description"].ToString());
if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["DeviceID"].ToString());
if (obj["PNPDeviceID"] != null) Console.WriteLine("PNPDeviceID:\t" + obj["PNPDeviceID"].ToString());
}
(see MSDN WMI tasks examples) for this)
or have a look into any COM ConnectedDevice
ManagementScope sc =
new ManagementScope(@"\\YOURCOMPUTERNAME\root\cimv2");
ObjectQuery query =
new ObjectQuery("Select * from Win32_SerialPort");
searcher = new ManagementObjectSearcher(sc, query);
result = searcher.Get();
foreach (ManagementObject obj in result)
{
if (obj["Caption"] != null) Console.WriteLine("Caption:\t" + obj["Description"].ToString());
if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["DeviceID"].ToString());
if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["PNPDeviceID"].ToString());
}
(see ActiveX Experts for further details on this)