如何获得串口设备ID?

在这个程序中,我首先尝试连接到availablelbe端口。 找到并连接后,我想读取连接的USB设备ID和供应商ID,我该怎么做?

亲切的问候

Program() { // Get a list of serial port names. string[] ports = SerialPort.GetPortNames(); // Search for the right port. foreach (string port in ports) { _serialPort = new SerialPort(port, 250000, Parity.None, 8, StopBits.One); _serialPort.Handshake = Handshake.None; _serialPort.ReadTimeout = 300; _serialPort.WriteTimeout = 300; try { _serialPort.Open(); break; } catch (Exception e) { Console.WriteLine("Serial port " + port + ": " + e.Message); } } /* ENTER CODE TO GET ID HERE */ Console.WriteLine("Using: " + _serialPort.PortName); Console.WriteLine("Device ID: " + _serialPort.DeviceID); 

几天前我终于把自己整理好了。 有两个部分,一个用于检查注册表,另一个用于检查设备的vid / pid。

我使用的注册表方法只是为了确保我不捕获像com0com这样的零调制解调器模拟器。

  ///  /// Removes any comm ports that are not explicitly defined as allowed in ALLOWED_TYPES ///  /// reference to List that will be checked ///  private static void nullModemCheck(ref List allPorts) { // Open registry to get the COM Ports available with the system RegistryKey regKey = Registry.LocalMachine; // Defined as: private const string REG_COM_STRING ="HARDWARE\DEVICEMAP\SERIALCOMM"; regKey = regKey.OpenSubKey(REG_COM_STRING); Dictionary tempDict = new Dictionary(); foreach (string p in allPorts) tempDict.Add(p, p); // This holds any matches we may find string match = ""; foreach (string subKey in regKey.GetValueNames()) { // Name must contain either VCP or Seial to be valid. Process any entries NOT matching // Compare to subKey (name of RegKey entry) if (!(subKey.Contains("Serial") || subKey.Contains("VCP"))) { // Okay, this might be an illegal port. // Peek in the dictionary, do we have this key? Compare to regKey.GetValue(subKey) if(tempDict.TryGetValue(regKey.GetValue(subKey).ToString(), out match)) { // Kill it! allPorts.Remove(match); // Reset our output string match = ""; } } } regKey.Close(); } 

video/ pid部分是从techinpro收集的

  ///  /// Compile an array of COM port names associated with given VID and PID ///  /// string representing the vendor id of the USB/Serial convertor /// string representing the product id of the USB/Serial convertor ///  private static List getPortByVPid(String VID, String PID) { String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID); Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase); List comports = new List(); 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")); } } } } return comports; }