gpt4 book ai didi

c# - 如何检索USB设备的名称

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:49 24 4
gpt4 key购买 nike

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

Exmaple of usb-device

在得到这些方法之前,我浏览了 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; }

}

非常感谢您的帮助

最佳答案

除了查询 Win32_USBHub,您可以尝试 Win32_PnPEntity。这将返回所有即插即用设备,因此我添加了一个过滤器以删除所有设备 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();
}
}

关于c# - 如何检索USB设备的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com