C# 获取计算机串口列表

C# 获取计算机串口列表功能实现。
第一步:引入库文件:"kernel32.dll"

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]

第二步:获取串口列表(两种方法)
方法一:从计算机注册表的特定位置读取出串口信息。返回:从注册表获取系统串口列表
public static string[] GetComList() { try { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); #if TEST OutputDebugString(keyCom.ToString()); #endif string[] sSubKeys = keyCom.GetValueNames(); string[] rtn = new string[sSubKeys.Length]; for (int i = 0; i < sSubKeys.Length; i++) { rtn[i] = (string)keyCom.GetValue(sSubKeys[i]); } return rtn; } catch (Exception e) { #if TEST OutputDebugString(e.Message); #endif return null; } }

方法二:利用.NET下提供的SerialPort类具体如下
public static string[] GetPort() { try { RegistryKey hklm = Registry.LocalMachine; RegistryKey software11 = hklm.OpenSubKey("HARDWARE"); //打开"HARDWARE"子健 RegistryKey software = software11.OpenSubKey("DEVICEMAP"); RegistryKey sitekey = software.OpenSubKey("SERIALCOMM"); #if TEST OutputDebugString(sitekey.ToString()); #endif //获取当前子健 String[] Str2 = sitekey.GetValueNames(); //获得当前子健下面所有健组成的字符串数组 int ValueCount = sitekey.ValueCount; //获得当前子健存在的健值 int i; string[] rtn = new string[ValueCount]; for (i = 0; i < ValueCount; i++) { rtn[i] = (string)sitekey.GetValue(Str2[i]); } return rtn; } catch (Exception e) { #if TEST OutputDebugString(e.Message); #endif return null; } }

【C# 获取计算机串口列表】

    推荐阅读