c# - 如何在 C# 中查找 USB 设备?

标签 c# .net visual-studio-2010 usb

我需要遍历连接到计算机的端口,并找到特定的设备。请看下图:

enter image description here

您可以看到有 4 个设备名称具有相同的供应商和产品 ID。但是,我需要找到第一个以蓝色突出显示的端口。似乎他们唯一的区别是 friend 名(描述是 friend 名)。

在 C#.net 中实现此目的的最简单方法是什么?我在“qt”中完成了此操作,我需要知道如何使用 vs 2010 专业版在 C#、.net Framework 4 中完成此操作。我已经完成了类似 this 的问题但如您所见,它们对我的情况毫无帮助。

最佳答案

如果您使用 libusbdotnet你应该能够做这样的事情:

public static void RetrieveUSBDevices(int vid, int pid)
{
        var usbFinder = new UsbDeviceFinder(vid, pid);
        var usbDevices = new UsbRegDeviceList();
        usbDevices = usbDevices.FindAll(usbFinder);
}

然后您应该能够迭代 usbDevices 并检查正确的 FullName .虽然还没有测试过,所以这是理论上的。

更新: 试过了,效果很好——问题是什么?为什么因为自己的无能而投反对票?

这也行:

private static void Method()
{
var list = GetMyUSBDevices();
//Iterate list here and use Description to find exact device
}


private static List<UsbDevice> GetMyUSBDevices()
{
    var vid = 32903;
    var pid = 36;

    ManagementObjectCollection collection;
    using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub"))
        collection = searcher.Get();

    var usbDevice = 
        (from ManagementBaseObject device in collection 
        select new UsbDevice(
        (string) device.GetPropertyValue("DeviceID"), 
        (string) device.GetPropertyValue("Description"))).ToList();

    var devices = new List<UsbDevice>();

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

    collection.Dispose();

    return (from d in devices where d.DeviceId.Contains("VID_") && d.DeviceId.Contains("PID_") && d.PID.Equals(pid) && d.VID.Equals(vid) select d).ToList();
}

public class UsbDevice
{
    public UsbDevice(string deviceId, string description)
    {
        DeviceId = deviceId;
        Description = description;
    }

    public string DeviceId { get; private set; }
    public string Description { get; private set; }

    public int VID 
    {
        get { return int.Parse(GetIdentifierPart("VID_"), System.Globalization.NumberStyles.HexNumber); }
    }

    public int PID
    {
        get { return int.Parse(GetIdentifierPart("PID_"), System.Globalization.NumberStyles.HexNumber); }
    }

    private string GetIdentifierPart(string identifier)
    {
        var vidIndex = DeviceId.IndexOf(identifier, StringComparison.Ordinal);
        var startingAtVid = DeviceId.Substring(vidIndex + 4);
        return startingAtVid.Substring(0, 4);
    }
}

关于c# - 如何在 C# 中查找 USB 设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18202392/

相关文章:

c# - WebClient.DownloadFile路径问题

c++ - 'LIBCMT' 与使用其他库 + 未解析的外部符号冲突

c# - 检测 RadGrid 项目展开/折叠状态的变化

javascript - MVC 4操作链接弹出框确认删除?

.net - 具有不同程序集版本的二进制反序列化

c# - 垃圾收集运行时如何调用析构函数 [.NET]?

c# - 即使对于 32 位,“编辑并继续”在 VS2010 中也不起作用

visual-studio - VS2010 - 2 个项目,1 个解决方案 - 在 1 个实例下调试两者

c# - 应用程序池身份与模拟身份?

c# - 本地 IPEndPoint 创建的端口选择。端口号重要吗?