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

How to Retrieve Serial Port Descriptions in C#?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 10:48:021089browse

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>

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!

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