This project is read-only.

Example: Query available COM-Ports

You can use the library to enumerate devices of certain device classes. The following example demonstrates, how easy it is to retrieve a list of available COM-Ports.

class ComPort
{
    public string DevicePath { get; set; }

    public string FriendlyName { get; set; }

    public string Description { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<ComPort> ports = GetComPorts();
        foreach (var port in ports)
            Console.WriteLine("{0}, Path: {1}", port.FriendlyName, port.DevicePath);

        Console.ReadKey();
    }

    private static IEnumerable<ComPort> GetComPorts()
    {
        var ports = new List<ComPort>();

        DeviceInterface deviceInterface = new DeviceInterface(DeviceInterfacesClasses.GUID_DEVINTERFACE_COMPORT);
        using (DeviceInfoSet set = DeviceInfoSet.GetPresent(deviceInterface))
        {
            foreach (DeviceInfo device in set.GetDevices())
            {
                ComPort port = new ComPort() { FriendlyName = device.FriendlyName, Description = device.Description };

                DeviceInterfaceData deviceInterfaceData;
                if ((deviceInterfaceData = set.GetDeviceInterfaceData(device).FirstOrDefault()) != null)
                    port.DevicePath = deviceInterfaceData.DevicePath;
            
                ports.Add(port);
            }
        }

        return ports.AsReadOnly();
    }
}

Last edited Aug 28, 2011 at 5:45 PM by mfriedrich, version 3

Comments

No comments yet.