c#自动获取对应的串口

下面是根据设备VID和PID匹配对应的串口,也可以根据设备的GUID匹配;具体实现返回类似字符串类似“COM1”。
注释部分可以打印出该设备的所有信息,方便查看选择自己需要的进行扩展。

/// /// VID+PID gets the serial port /// /// private string searchDevicesRegistry() { string[] available_spectrometers = SerialPort.GetPortNames(); ManagementObjectCollection.ManagementObjectEnumerator enumerator = null; string commDatahttps://www.it610.com/article/= ""; ManagementObjectSearcher mObjs = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM WIN32_PnPEntity"); try { enumerator = mObjs.Get().GetEnumerator(); while (enumerator.MoveNext()) { ManagementObject current = (ManagementObject)enumerator.Current; if (Strings.InStr(Conversions.ToString(current["Caption"]), "(COM", CompareMethod.Binary) <= 0) { continue; } //foreach (var property in current.Properties) //{ //Console.WriteLine(property.Name + ":" + property.Value); //} if (current["DeviceID"].ToString().Equals(@"FTDIBUS\VID_0413+PID_6111+FTZ6XM7RA\0000"))) { commData = https://www.it610.com/article/current["Name"].ToString().Substring(17,4); break; } } } finally { if (enumerator != null) { enumerator.Dispose(); } } return commData; }


‘设备管理器‘里察看USB设备属性的PID和VID,也可以百度科普一下。
这是使用到的动态库using System.IO.Ports;
using System.Management;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
【c#自动获取对应的串口】??

    推荐阅读