Home  >  Article  >  Backend Development  >  How Do I Retrieve Serial Port Descriptions in C#?

How Do I Retrieve Serial Port Descriptions in C#?

DDD
DDDOriginal
2024-10-31 10:26:28997browse

How Do I Retrieve Serial Port Descriptions in C#?

Retrieving Serial Port Details

The provided code successfully enumerates COM ports, but it lacks the functionality to retrieve port descriptions like those visible in Device Manager. For a comprehensive solution, the following approach is recommended:

<code class="csharp">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 (string s in portList)
    {
        Console.WriteLine(s);
    }
}</code>

The above code utilizes Windows Management Instrumentation (WMI) to gather detailed information about each serial port. The ManagementObjectSearcher is configured to query for specific COM port information.

The SerialPort.GetPortNames() method returns an array of port names. These names are then used to filter the WMI query and retrieve the corresponding port descriptions.

The resulting list portList contains a combination of port names and descriptions. By iterating through this list, you can display the information as desired, for instance, in a combo box to provide users with a descriptive list of available serial ports.

The above is the detailed content of How Do I Retrieve Serial Port Descriptions in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn