看图说话。
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Management; // need to add System.Management to your project references.
class Program
{
static void Main(string[] args)
{
var usbDevices = GetUSBDevices();
foreach (var usbDevice in usbDevices)
{
Console.WriteLine("Device ID: {0}, PNP Device ID: {1}, Description: {2}",
usbDevice.DeviceID, usbDevice.PnpDeviceID, usbDevice.Description);
}
Console.Read();
}
static List<USBDeviceInfo> GetUSBDevices1()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"SELECT * FROM Win32_PnPEntity where DeviceID Like ""USB%"""))
collection = searcher.Get();
foreach (var device in collection)
{
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
static List<USBDeviceInfo> GetUSBDevices()
{
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
ManagementObjectCollection collection;
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
collection = searcher.Get();
List<object> listObj = new List<object>();
List<string> listStr = new List<string>();
foreach (var device in collection)
{
var tmp = device.Properties;
foreach(var v in tmp)
{
listStr.Add(v.Name);
listObj.Add(device.GetPropertyValue(v.Name));
}
devices.Add(new USBDeviceInfo(
(string)device.GetPropertyValue("DeviceID"),
(string)device.GetPropertyValue("PNPDeviceID"),
(string)device.GetPropertyValue("Description")
));
}
collection.Dispose();
return devices;
}
}
class USBDeviceInfo
{
public USBDeviceInfo(string deviceID, string pnpDeviceID, string description)
{
this.DeviceID = deviceID;
this.PnpDeviceID = pnpDeviceID;
this.Description = description;
}
public string DeviceID { get; private set; }
public string PnpDeviceID { get; private set; }
public string Description { get; private set; }
}
}
}
输出结果:
Device ID: USB\ROOT_HUB30\4&25FCAC55&0&0, PNP Device ID: USB\ROOT_HUB30\4&25FCAC55&0&0, Description: USB 根集线器(USB 3.0)
Device ID: USB\VID_0C45&PID_671E\5&1A4E9922&0&6, PNP Device ID: USB\VID_0C45&PID_671E\5&1A4E9922&0&6, Description: USB Composite Device
Device ID: USB\VID_1C4F&PID_0002\5&1A4E9922&0&1, PNP Device ID: USB\VID_1C4F&PID_0002\5&1A4E9922&0&1, Description: USB Composite Device
第一行 USB\ROOT_HUB30\4&25FCAC55&0&0,中的数字与USB的位置相关。