winform 获取可用的串口(包括串口名称)

SerialPort.GetPortNames() 也可以获取可用的串口,但是只有COM1、COM2 这种,下面的代码是另一种获取串口的方式,可以获取到驱动名称之类的设备名

using System;
using System.Collections.Generic;
using System.Management;
using System.Text.RegularExpressions;

namespace Example
{
    internal class Example
    {
        public static List GetComList()
        {
            List list = new List();
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity"))
            using(ManagementObjectCollection.ManagementObjectEnumerator enumerator = searcher.Get().GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    ManagementBaseObject current = enumerator.Current;
                    if (current.Properties["Name"].Value != null)
                    {
                        string text = current.Properties["Name"].Value.ToString();
                        Match m = Regex.Match(text, @"COM\d+");
                        if (m.Success)
                        {
                            Console.WriteLine(new string('*', 100));
                            //获取的是这样子的:通信端口 (COM1)
                            //我们给转成这样子:COM1 通信端口
                            string item = $"{m.Value} {text.Substring(0, m.Index - 1)}".Trim();
                            Console.WriteLine(item);
                            list.Add(item);
                        }
                    }
                }
                return list;
            }
        }

    }
}

你可能感兴趣的:(Windows桌面应用,windows)