QUEST LOG · April 28, 2020· UPDATED June 2, 2026

Auto-Connecting a SerialPort in C# by VID and PID

The C# serial port function's official example ↗ looks something like this

C#
streamport = new SerialPort("COM3", bauadrate);

With this approach you have to go change the port every single time you open it, which is a real pain. So I found a function someone else wrote for Windows that returns a static port string to SerialPort, and it works really well.

C#
// 有錯誤可能是你沒有 using Microsoft.Win32;或其他lib
 public static List<string> ComPortNames(String VID, String PID)
    {
        // 讀取PID和VID
        String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
        Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
        List<string> comports = new List<string>();
        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");
        foreach (String s3 in rk2.GetSubKeyNames())
        {
            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        comports.Add((string)rk6.GetValue("PortName"));
                        // 獲取port name,如有多個相同設備,加入comports array
                    }
                }
            }
        }
        return comports;
    }

See the link below for the full details😁
Code source ↗

Apps I ship

Free on iOS and Android.

Solid(ar)ity

Solid(ar)ity

A privacy-first identity wallet: zero-knowledge proofs and signed cards swapped face to face, no central server.