Home  >  Article  >  Backend Development  >  How Can I Retrieve Serial Port Information Including Descriptions in C#?

How Can I Retrieve Serial Port Information Including Descriptions in C#?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 15:23:02246browse

How Can I Retrieve Serial Port Information Including Descriptions in C#?

How to Retrieve Serial Port Information in C

To populate a combo box with serial port names, developers often use SerialPort.GetPortNames(). However, users have expressed the need to include port descriptions as well. Here's how to accomplish this:

<code class="csharp">using System;
using System.Management;

class Program
{
    static void Main(string[] args)
    {
        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>

By leveraging WMI (Windows Management Instrumentation), this solution queries for PNP (Plug and Play) entities containing "COM" in their captions. The resulting list of ports and descriptions is then displayed or can be loaded into a combo box as needed.

The above is the detailed content of How Can I Retrieve Serial Port Information Including 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