Does C# provide an effective means of scanning the available COM ports? I would like to have a dropdown list in my application wherein the user can select one of the detected COM ports. Creating and populating the dropdown list is not a problem. I just need to know how to scan for the available COM ports using C#. I am using Microsoft Visual C# 2008 Express Edition. Thanks.
+2
A:
System.IO.Ports is the namespace you want.
SerialPort.GetPortNames will list all serial COM ports.
Unfortunately, parallel ports are not supported directly from C#, as they're very infrequently used except in legacy situations. That said, you can list them by querying the following registry key:
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\PARALLEL PORTS
See the Microsoft.Win32 namespace for details.
Randolpho
2010-03-30 20:57:37
Thanks for the additional details, but I'm really only interested in listing the serial COM ports (not legacy parallel).
Jim Fell
2010-03-30 21:48:54
@Jim Fell: I figured as much the first time I posted, but on second thought decided to be explicit about parallel, just in case.
Randolpho
2010-03-30 21:53:26
A:
Use WMI through the System.Management namespace. A quick Google finds this code:
using System;
using System.Management;
public class Foo
{
public static void Main()
{
var instances = new ManagementClass("Win32_SerialPort").GetInstances();
foreach ( ManagementObject port in instances )
{
Console.WriteLine("{0}: {1}", port["deviceid"], port["name"]);
}
}
James Westgate
2010-03-30 21:02:06