Home > Backend Development > C++ > How to Retrieve Serial Port Descriptions in C#?

How to Retrieve Serial Port Descriptions in C#?

Susan Sarandon
Release: 2024-10-29 10:48:02
Original
1082 people have browsed it

How to Retrieve Serial Port Descriptions in C#?

Retrieving Serial Port Descriptions

The supplied code effectively loads serial port names into a combo-box. To enhance this functionality, acquiring the corresponding port descriptions is desirable. This article presents an approach for obtaining such descriptions using the ManagementObjectSearcher class in Microsoft.Management namespace.

<code class="c#">using Microsoft.Management;

...

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:

  • Creates a ManagementObjectSearcher to query for all PnP entities whose captions contain "(COM".
  • Obtains an array of port names using SerialPort.GetPortNames().
  • Maps the port names to their corresponding captions using the searcher.
  • Formats the port names and captions in the desired format.
  • Displays the extended list with port descriptions.

The above is the detailed content of How to 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template