PortUtil.cs 1.7 KB

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