【发布时间】:2019-08-16 15:16:51
【问题描述】:
我正在尝试获取已连接的 USB 设备的名称,例如手机或 USB 记忆棒。
在获得这些方法之前,我浏览了 stackoverflow,但找不到合适的属性。
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;
}
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; }
}
非常感谢您的帮助
【问题讨论】:
-
"但是我找不到合适的属性。"什么意思?
-
我喜欢以手机名称“kai”为例。该名称属性仅给我“USB-Root-Hub”或“Generic USB Hub”等。
-
您可能希望使用与 wmi 不同的库来获取该信息
-
@DanielA.White 你有什么建议适合哪个图书馆吗?
-
不同的 USB 设备使用不同的属性。所以对于不同的设备可能不一样。有些设备甚至没有 Name 属性。