using System; using System.Collections.Generic; using System.Text; using System.IO; using System.IO.Ports; using Microsoft.Win32; namespace ComPortCapture { class Program { static void Main(string[] args) { List pname = FindPort("USB"); foreach (string[] p in pname) { Console.WriteLine(p[0].ToString()); Console.WriteLine(p[1].ToString()); } Console.WriteLine("bye\n"); } static List FindPort(string pattern) { // get all the possible registry entries List portList = new List(); RegistryKey rk = Registry.LocalMachine.OpenSubKey("SYSTEM\\ControlSet001\\Enum"); GetKeys(rk, portList, "Class", "Ports"); //foreach (String s in portList) // Console.WriteLine("<" + s + ">"); // get all teh possible serial ports present string[] serial = SerialPort.GetPortNames(); List found = new List(); foreach (string p in serial) Console.WriteLine("<" + p + ">"); foreach (string port in serial) { foreach (String s in portList) { string[] a = {port,s}; if (s.Contains(port) && s.Contains(pattern)) found.Add(a); } } return found; } static void GetKeys(RegistryKey rkey, List plist, string name, string value) { // check for any value fields if (rkey.ValueCount > 0) { // get all the value names string[] vnames = rkey.GetValueNames(); // find value name matching the pattern foreach (string v in vnames) if (v.Equals(name) && rkey.GetValue(v).Equals(value)) { plist.Add(rkey.GetValue("FriendlyName").ToString()); } } // check for any subkeys if (rkey.SubKeyCount > 0) { // get all the subkey names string [] knames = rkey.GetSubKeyNames(); // loop through all the subkeys recursively foreach (string s in knames) { RegistryKey key = rkey.OpenSubKey(s); if (key.Equals(null)) continue; GetKeys(key, plist, name, value); } } // end of GetKeys } } }