以编程方式获得友好的端口名称

时间:2012-02-21 01:20:14

标签: c# vb.net serial-port

这里的任何人都知道我可以在PC上找到端口名称吗?

List of ports provided by Device Manager

使用此代码:

For i As Integer = 0 To My.Computer.Ports.SerialPortNames.Count - 1
    cmbPort.Properties.Items.Add(My.Computer.Ports.SerialPortNames(i))
Next

我可以获得COM26等等,但这不是我想要的。我想要COM26USB-SERIAL CH340,而不是检索USB-SERIAL CH340 (COM26)。我怎么能这样做?

4 个答案:

答案 0 :(得分:8)

我从其他答案得到的结果好坏参半。 我已经提出这个代码对我来说更好。

在您的应用程序中添加对System.Management的引用

using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
{
    var portnames = SerialPort.GetPortNames();
    var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

    portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
}

答案 1 :(得分:6)

试试这个。

Public Shared Function ListFriendlyCOMPOrt() As List(Of String)

    Dim oList As New List(Of String)

    Try
        Using searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM26%'")
            For Each queryObj As ManagementObject In searcher.Get()
                oList.Add(CStr(queryObj("Caption")))
            Next
        End Using

        Return oList

    Catch err As ManagementException
        MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
    End Try

    Return oList

End Function

那应该有用..

答案 2 :(得分:2)

您可以使用WMI ... 在应用程序中添加对System.Management的引用 然后,

StackOverflow上显示的

Getting Serial Port Information

using System.Management;
using System.IO;

        string result = "";
        using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
        {
            string[] portnames = SerialPort.GetPortNames();
            var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
            var tList = (from n in portnames join p in ports on n equals p["DeviceID"].ToString() select n + " - " + p["Caption"]).ToList();

            foreach (string s in tList)
            {
                result = result + s;
            }
        }
        MessageBox.Show(result);

答案 3 :(得分:0)

这不是串口的名称;这是COM26。设备管理器中列出的名称可能是提供仿真的设备的名称。

为什么要这个名字?如果您更完整地描述您的问题,找出解决方案会更容易。