Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET FRIENDLY PORT NAME Programmatically

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?

like image 261
John Woo Avatar asked Feb 21 '12 01:02

John Woo


1 Answers

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());

    var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
    foreach (var i in portList)
    {
        Console.WriteLine(i);
    }
}
like image 53
Guillermo Ruffino Avatar answered Sep 22 '22 20:09

Guillermo Ruffino