C# 已知PID VID,自动查找USB串口号

已知PID VID,自动查找USB串口号的方法:

增加如下using

using System.IO.Ports;

using System.Management;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;

添加引用System.ManagementC# 已知PID VID,自动查找USB串口号_第1张图片

添加引用Microsoft.VisualBasic

C# 已知PID VID,自动查找USB串口号_第2张图片

 


            string[] available_spectrometers = SerialPort.GetPortNames();
            ManagementObjectCollection.ManagementObjectEnumerator enumerator = null;
            string commData = "";
            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;
                    }
                }
            }
            finally
            {
                if (enumerator != null)
                {
                    enumerator.Dispose();
                }
            }
            return commData;//返回串口号
 

完整代码请见:

你可能感兴趣的:(C#)