[英]Mapping USB device name to com port in C#?
我有一个USB设备,提供虚拟COM端口。 但是,此设备不会通过COM端口“友好名称”(例如,在Windows单元管理器中)标识自己。
但它确实为USB设备提供了正确的名称。 其中依次列出相关的com端口,如下所示:
我希望能够通过名称识别设备(“Prologix GPIB ...”)并从该名称获取com端口号。 我怎么能用C#/ .NET做到这一点?
我能够找到的唯一代码只能通过COM端口友好名称搜索,而不是USB设备名称。
谢谢你的时间!
我没有虚拟COM端口设置,所以不能检查这一点,但在其中一个答案这篇文章似乎适合您的要求:
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> 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")
));
}
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; }
}
这适用于列出我的设备。 您可能需要在GetUSBDevices
试验其他PropertyValue
字段以查找虚拟COM端口名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.