如何检索USB设备的名称

How to retrieve the name of an usb device

我正在尝试获取连接的 USB 设备的名称,例如手机或 U 盘。

因为我在得到这些方法之前浏览了Whosebug,但是我找不到合适的属性。

static List<USBDeviceInfo> GetUSBDevices()
{
    List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
    ManagementObjectCollection collection;
    using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
        collection = searcher.Get();

        foreach (var device in collection)
        {
            devices.Add(new USBDeviceInfo(
            (string)device.GetPropertyValue("DeviceID"),
            (string)device.GetPropertyValue("PNPDeviceID"),
            (string)device.GetPropertyValue("Description"),
            (string)device.GetPropertyValue("Name"),
            (string)device.GetPropertyValue("Caption")
            ));
        }

        collection.Dispose();
        return devices;
}

Class USBDeviceInfo:

class USBDeviceInfo
{
    public USBDeviceInfo(string deviceID, string pnpDeviceID, string description, string name, string caption)
    {
        this.DeviceID = deviceID;
        this.PnpDeviceID = pnpDeviceID;
        this.Description = description;
        this.Name = name;
        this.Caption = caption;
    }
    public string DeviceID { get; private set; }
    public string PnpDeviceID { get; private set; }
    public string Description { get; private set; }
    public string Name { get; private set; }
    public string Caption { get; private set; }

}

非常感谢您的帮助

您可以尝试 Win32_PnPEntity 而不是查询 Win32_USBHub。这 returns 所有即插即用设备,因此我添加了一个过滤器以删除任何设备 ID 不以 "USB" 开头的设备。可能有更好的方法,但我过去使用过,所以我会在这里分享。

这是您的代码的修改版本:

class USBDeviceInfo
{
    public USBDeviceInfo(string deviceId, string name, string description)
    {
        DeviceId = deviceId;
        Name = name;
        Description = description;
    }

    public string DeviceId { get; }
    public string Name { get; }
    public string Description { get; }

    public override string ToString()
    {
        return Name;
    }
}

public class Program
{
    static List<USBDeviceInfo> GetUSBDevices()
    {
        var devices = new List<USBDeviceInfo>();

        using (var mos = new ManagementObjectSearcher(@"Select * From Win32_PnPEntity"))
        {
            using (ManagementObjectCollection collection = mos.Get())
            {
                foreach (var device in collection)
                {
                    var id = device.GetPropertyValue("DeviceId").ToString();

                    if (!id.StartsWith("USB", StringComparison.OrdinalIgnoreCase)) 
                        continue;

                    var name = device.GetPropertyValue("Name").ToString();
                    var description = device.GetPropertyValue("Description").ToString();
                    devices.Add(new USBDeviceInfo(id, name, description));
                }
            }
        }

        return devices;
    }

    private static void Main()
    {
        GetUSBDevices().ForEach(Console.WriteLine);

        Console.ReadKey();
    }
}