我有一个提供虚拟COM端口的USB设备。但是,此设备不会通过COM端口“友好名称”(例如,在Windows单元管理器中)标识自己。
但它确实为USB设备提供了正确的名称。其中依次列出了相关的com端口:
我希望能够通过名称识别设备(“Prologix GPIB ...”)并从该名称获取com端口号。我怎么能在C#/ .NET中做到这一点?
我能找到的唯一代码只能通过COM端口友好名称搜索,而不是USB设备名称。
谢谢你的时间!
答案 0 :(得分:3)
我没有设置虚拟COM端口,因此无法检查,但this article中的一个答案似乎符合您的要求:
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; }
}
这适用于列出我的设备。您可能需要尝试PropertyValue
中的其他GetUSBDevices
字段来查找虚拟COM端口名称。