PortUtil.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO.Ports;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. namespace DeviceCenter
  10. {
  11. class PortUtil
  12. {
  13. public static List<string> FindComPortNames(String VID, String PID)
  14. {
  15. String pattern = String.Format("^VID_{0}.PID_{1}", VID, PID);
  16. Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
  17. List<string> comports = new List<string>();
  18. RegistryKey rk1 = Registry.LocalMachine;
  19. RegistryKey rk2 = rk1.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum");
  20. foreach (String s3 in rk2.GetSubKeyNames())
  21. {
  22. RegistryKey rk3 = rk2.OpenSubKey(s3);
  23. foreach (String s in rk3.GetSubKeyNames())
  24. {
  25. if (_rx.Match(s).Success)
  26. {
  27. RegistryKey rk4 = rk3.OpenSubKey(s);
  28. foreach (String s2 in rk4.GetSubKeyNames())
  29. {
  30. RegistryKey rk5 = rk4.OpenSubKey(s2);
  31. string location = (string)rk5.GetValue("LocationInformation");
  32. RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
  33. string portName = (string)rk6.GetValue("PortName");
  34. if (!String.IsNullOrEmpty(portName) && SerialPort.GetPortNames().Contains(portName))
  35. comports.Add((string)rk6.GetValue("PortName"));
  36. }
  37. }
  38. }
  39. }
  40. return comports;
  41. }
  42. }
  43. }