1.效果图:

2.代码
class Program { static void Main(string[] args) { GetComList(); } private static void GetComList() {try { using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity")) { Console.WriteLine("本机串口:"); var hardInfos = searcher.Get(); int index = 1; foreach (var hardInfo in hardInfos) { if (hardInfo.Properties["Name"].Value != null && hardInfo.Properties["Name"].Value.ToString().Contains("(COM")) { String strComName = hardInfo.Properties["Name"].Value.ToString(); Console.WriteLine(index + ":" + strComName);//打印串口设备名称及串口号 index += 1; } } } Console.ReadKey(); } catch { } } }
本文介绍了一个使用C#编写的简单程序,该程序能够通过调用WMI(Windows Management Instrumentation)来获取并列出当前计算机上的所有串口设备。通过这个示例代码,开发者可以了解到如何利用ManagementObjectSearcher类检索Win32_PnPEntity信息,并筛选出与串口相关的设备。
623

被折叠的 条评论
为什么被折叠?



