Home >Backend Development >C++ >How Can I Retrieve Serial Port Information Including Descriptions 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!