Thursday, 8 September 2011

Retrieving available COM ports

I recently had to deal with a dodgy USB driver that didn't null-terminal it's virtual com-ports in the registry. As a result, when retrieving the ports-list via the usual SerialPort.GetPortNames(), I got values like "COM7รข".

Here's a little method to not only remove any unwanted characters from the port-names, but (using an anonymous delegate to implement an IComparer on the Sort() extension method) order the list of COM ports by port-number too (otherwise COM11 would come before COM2):

/// <summary>
/// Returns a list of available comports sorted in order of port number
/// </summary>
/// <remarks>
/// Also trims any non alpha-numeric characters from the port name
/// </remarks>
public static List<string> GetAvailablePortsSorted()
{
    List<string> availablePorts = SerialPort.GetPortNames().ToList();

    for (int i = 0; i < availablePorts.Count; i++)
    {
        // Trim any non-alphanumeric characters from the port name
        availablePorts[i] = Regex.Replace(availablePorts[i], "[^A-Za-z0-9]", "");    
    }

    try
    {
        availablePorts.Sort(
            delegate(string strA, string strB)
            {
                int idA = int.Parse(strA.Substring(3)),
                idB = int.Parse(strB.Substring(3));
                return idA.CompareTo(idB);
            });
    }
    catch { };  

    return availablePorts;
}

No comments:

Post a Comment