I need to track the USB insertion and removal events from the C# application so I came up with the following ideas based on the other questions on SO.
I can't use this method
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable).ToList();
because it can lead to a lot of troubles when you need to differentiate between connected and disconnected devices (the new ones can have the same drive letter and name like the ones that was previously cached).
So I decided to use WMI to solve this problem but I found that it's impossible to get the drive letter of the specified USB device via Win32_USBHub
class. Then I thought that I can execute another query like this
foreach (ManagementObject device in new ManagementObjectSearcher(@"SELECT * FROM Win32_USBHub").Get())
{
string deviceID = (string)device.GetPropertyValue("DeviceID");
Console.WriteLine("{0}", deviceID);
string query = string.Format("SELECT * FROM Win32_LogicalDisk WHERE DeviceID='{0}'", deviceID);
foreach (ManagementObject o in new ManagementObjectSearcher(query).Get())
{
string name = (string)o.GetPropertyValue("Name");
Console.WriteLine("{0}", name);
}
Console.WriteLine("==================================");
}
but it doesn't work at all -- I get an exception "Invalid query" every time when I try to execute query that works with the Win32_LogicalDisk
table.
Why? What am I doing wrong? How can I fix it? Maybe there is a better ways to solve this problem?
Thanks in advance.