Home > Backend Development > C++ > body text

How Do I Retrieve Serial Port Descriptions in C#?

DDD
Release: 2024-10-31 10:26:28
Original
996 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!