Feedback

Sortierte Liste der seriellen Ports

Sprache: VB

Die Funktion IO.Ports.SerialPort.GetPortNames() liefert nur eine unsortierte Liste. Das Snippet sortiert die Liste so, das auch die COM-Ports 1-9 vor 10… stehen.
Dim astrCOMPorts As String() = {}

astrCOMPorts = IO.Ports.SerialPort.GetPortNames()

If astrCOMPorts.Length > 0 Then
  ' für alle COM-Nr. < 10 ein Leerzeichen einfügen
  For i As Integer = 0 To (astrCOMPorts.Length - 1)
    If CInt(astrCOMPorts(i).Substring(3)) < 10 Then
      astrCOMPorts(i) = "COM " & astrCOMPorts(i).Substring(3)
    End If
  Next

  Array.Sort(astrCOMPorts)

  ' das Leerzeichen in "COM x" wieder entfernen
  For i As Integer = 0 To (astrCOMPorts.Length - 1)
    astrCOMPorts(i) = "COM" & astrCOMPorts(i).Substring(3).Trim
  Next
End If
Dim astrCOMPorts As String() = {}

astrCOMPorts = IO.Ports.SerialPort.GetPortNames()

If astrCOMPorts.Length > 0 Then
  ' für alle COM-Nr. < 10 ein Leerzeichen einfügen
  For i As Integer = 0 To (astrCOMPorts.Length - 1)
    If CInt(astrCOMPorts(i).Substring(3)) < 10 Then
      astrCOMPorts(i) = "COM " & astrCOMPorts(i).Substring(3)
    End If
  Next

  Array.Sort(astrCOMPorts)

  ' das Leerzeichen in "COM x" wieder entfernen
  For i As Integer = 0 To (astrCOMPorts.Length - 1)
    astrCOMPorts(i) = "COM" & astrCOMPorts(i).Substring(3).Trim
  Next
End If