I have some code that loads the serial ports into a combo-box:
List<String> tList = new List<String>(); comboBoxComPort.Items.Clear(); foreach (string s in SerialPort.GetPortNames()) { tList.Add(s); } tList.Sort(); comboBoxComPort.Items.Add("Select COM port..."); comboBoxComPort.Items.AddRange(tList.ToArray()); comboBoxComPort.SelectedIndex = 0;
I would like to add the port descriptions (similar to what are shown for the COM ports in the Device Manager) to the list and sort the items in the list that are after index 0 (solved: see above snippet). Does anyone have any suggestions for adding the port descriptions? I am using Microsoft Visual C# 2008 Express Edition (.NET 2.0). Any thoughts you may have would be appreciated. Thanks.
Open Windows Device Manager. Find "Ports (COM & LPT)" in the list. Expand "Ports (COM & LPT)" to see the names of all serial ports.
Locate the correct COM portRight click on the Windows Start Icon and select "Device Manager." Open the "Ports (COM & LPT)" Section. Locate the "PI USB to Serial" and note which COM port it is using.
EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...
Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)
Sample code (make sure to add reference to System.Management):
using System; using System.Management; using System.Collections.Generic; using System.Linq; using System.IO.Ports; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (var searcher = new ManagementObjectSearcher ("SELECT * FROM WIN32_SerialPort")) { string[] portnames = SerialPort.GetPortNames(); var ports = searcher.Get().Cast<ManagementBaseObject>().ToList(); var tList = (from n in portnames join p in ports on n equals p["DeviceID"].ToString() select n + " - " + p["Caption"]).ToList(); tList.ForEach(Console.WriteLine); } // pause program execution to review results... Console.WriteLine("Press enter to exit"); Console.ReadLine(); } } }
More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx
I tried so many solutions on here that didn't work for me, only displaying some of the ports. But the following displayed All of them and their information.
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); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With