GET FRIENDLY PORT NAME Programmatically

2020-03-04 07:31发布

Anyone here has an idea where I can get the ports name listed in my PC?

List of ports provided by Device Manager

By using this code:

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

I could get COM26 and etc. if any, but that's not what I want. Instead of retrieving COM26, I want USB-SERIAL CH340 or USB-SERIAL CH340 (COM26). How could I do that?

4条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-04 07:45

That isn't the name of the serial port; it is COM26. The name listed in the device manager is probably the name of the device providing the emulation.

Why do you want that name? If you describe your problem more completely, figuring out the solution will be easier.

查看更多
对你真心纯属浪费
3楼-- · 2020-03-04 07:48

You could use WMI... Add Reference to System.Management in your application then,

shown on 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);
查看更多
够拽才男人
4楼-- · 2020-03-04 08:01

I got mixed results from other answers. I've come up with this code working better for me.

Add Reference to System.Management in your application

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();
}
查看更多
We Are One
5楼-- · 2020-03-04 08:05

Try this .

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

That should work..

查看更多
登录 后发表回答