在c#中获取端口名称

本文关键字:获取 | 更新日期: 2023-09-27 18:15:38

我是嵌入式编程的新手,我试图在列表中获得所有端口名称。我想这是最基本的操作。

using System.IO.Ports;    
string[] ports = SerialPort.GetPortNames();

不知道这个基本操作在哪里出错,但是字符串是空的。

在c#中获取端口名称

GetPortNames将只收集有效连接的COM端口。

如果您试图收集一个断开连接的端口的COM端口,您将需要搜索注册表。以下是我如何找到我想要的基于VID和PID的正确设备。

public class ComPortFinder
{
    public static List<DeviceInfo> FindConnectedDevices(uint vid, uint pid)
    {
        string pattern = string.Format("^VID_{0:X4}.PID_{1:X4}", vid, pid);
        Regex _rx = new Regex(pattern, RegexOptions.IgnoreCase);
        List<DeviceInfo> devices = new List<DeviceInfo>();
        RegistryKey rk1 = Registry.LocalMachine;
        RegistryKey rk2 = rk1.OpenSubKey("SYSTEM''CurrentControlSet''Enum");
        foreach (String s3 in rk2.GetSubKeyNames())
        {
            RegistryKey rk3 = rk2.OpenSubKey(s3);
            foreach (String s in rk3.GetSubKeyNames())
            {
                if (_rx.Match(s).Success)
                {
                    RegistryKey rk4 = rk3.OpenSubKey(s);
                    foreach (String s2 in rk4.GetSubKeyNames())
                    {
                        RegistryKey rk5 = rk4.OpenSubKey(s2);
                        RegistryKey rk6 = rk5.OpenSubKey("Device Parameters");
                        if (!string.IsNullOrEmpty((string)rk6.GetValue("PortName")))
                        {
                            DeviceInfo di = new DeviceInfo()
                            {
                                VenderId = vid,
                                ProductId = pid,
                                SerialNumber = "UNKNOWN",
                                ComPort = rk6.GetValue("PortName").ToString()
                            };
                            devices.Add(di);
                        }
                    }
                }
            }
        }
        return devices;
    }
}
public struct DeviceInfo
{
    public uint VenderId;
    public uint ProductId;
    public string SerialNumber;
    public string ComPort;
}

我不认为这是功劳,因为我相信这是从另一个StackOverflow答案偷来的,但希望它能有所帮助。

根据Juanma的回答,您可以通过在这里使用wmi工具获得所有端口。如何找到可用的COM端口?

try
{
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher("root''WMI",
        "SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("MSSerial_PortName instance");
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("MSSerial_PortName instance");
    Console.WriteLine("-----------------------------------");
    Console.WriteLine("PortName: {0}", queryObj["PortName"]);
    //If the serial port's instance name contains USB 
    //it must be a USB to serial device
    if (queryObj["InstanceName"].ToString().Contains("USB"))
    {
        Console.WriteLine(queryObj["PortName"] + " 
        is a USB to SERIAL adapter/converter");
    }
}
}
catch (ManagementException e)
{
    MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}

不要忘记添加System。参考管理