Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-30 15:23:02
Original
256 people have browsed it

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

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!

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
Latest Articles by Author
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!