使用的命名控件
using System.Management;
代码
点击查看代码
/// <summary>
/// 获取串口的全称
/// </summary>
/// <returns></returns>
public static List<string> GetCompleteNameOfSerialPort() {
List<string> serial_port_result = new List<string>();
Dictionary<string, string> coms = new Dictionary<string, string>();
try {
string sql = "select * from Win32_PnPEntity";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(sql)) {
var hardInfos = searcher.Get();
if (null != hardInfos) {
foreach (var hardInfo in hardInfos) {
var hardProperty = hardInfo.Properties;
if (null != hardProperty) {
PropertyData hardProperty2 = hardProperty["Name"];
if (null != hardProperty2) {
string hardPropertyValue = (string)hardProperty2.Value;
if (!string.IsNullOrWhiteSpace(hardPropertyValue)) {
//是否为串口
string pattern = @"COM\d+";
if (Regex.IsMatch(hardPropertyValue, pattern)) {
Match match = Regex.Match(hardPropertyValue, pattern);
coms.Add(match.Value, hardPropertyValue);
}
}
}
}
}
}
}
foreach (string key in coms.Keys) {
string value = coms[key];
string listItem = string.Format("{0} {1}", key, value);
serial_port_result.Add(listItem);
}
}
catch (Exception ex) {
throw ;
}
return serial_port_result;
}