[英]Mapping USB device name to com port in C#?
I have a USB device that provides a virtual com port. 我有一个USB设备,提供虚拟COM端口。 However this device does not identify itself by a COM port "friendly name" (in windows unit manager for instance). 但是,此设备不会通过COM端口“友好名称”(例如,在Windows单元管理器中)标识自己。
However it does provide a proper name for the USB device. 但它确实为USB设备提供了正确的名称。 Which in turn lists the associated com port as follows: 其中依次列出相关的com端口,如下所示:
I'd like to be able to identify the device by name ("Prologix GPIB...") and get the com port number from that name. 我希望能够通过名称识别设备(“Prologix GPIB ...”)并从该名称获取com端口号。 How can i do this in C# / .NET? 我怎么能用C#/ .NET做到这一点?
The only code i was able to find only searched by the COM port friendly name, not the USB device name. 我能够找到的唯一代码只能通过COM端口友好名称搜索,而不是USB设备名称。
Thanks for your time! 谢谢你的时间!
I don't have virtual COM port set up, so can't check this, but one of the answers in this article seems to fit your requirement: 我没有虚拟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; }
}
This works fine for listing my devices. 这适用于列出我的设备。 You may need to experiment with additional PropertyValue
fields in GetUSBDevices
to find virtual COM port names. 您可能需要在GetUSBDevices
试验其他PropertyValue
字段以查找虚拟COM端口名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.