Hi All,

I'm doing some serial I/O in VB.NET for a project at work. I'm new to VB.NET so I'm not sure if I'm doing this correctly. I need to determine what ports are free and which ones are in use. Presently, I try to open the port and if there's an error I know that port is not available. I think there must be better way. See code below.

Thanks for your help,
Bill

Imports System.IO.Ports

Module Module1

    Sub Main()

        Dim PortName As String
        Dim port As New SerialPort

        Console.WriteLine("RS-232 ports on this computer:")

        For Each PortName In SerialPort.GetPortNames()
            If PortIsAvailable(PortName) Then
                Console.WriteLine(PortName + " is available.")
            Else
                Console.WriteLine(PortName + " is in use.")
            End If
        Next PortName

    End Sub

    Public Function PortIsAvailable(ByVal port As String) As Boolean
        Dim TempPort As New SerialPort
        TempPort.PortName = port
        'Surely there's a better way to test for availability
        'than trying to open the port and catching errors.
        Try
            TempPort.Open()
        Catch ex As UnauthorizedAccessException
            Return False
        End Try
        TempPort.Close()
        Return True
    End Function

End Module

There is really not that I can see, the longer way to do this is to use existing windows APIs. That is something like this:

Public Sub Open(ByVal portname As String, _
        ByVal Spd As Integer, ByVal Pty As enumParity, _
        ByVal Dtb As Integer, ByVal Stp As enumStopBits)

        Dim m_CommDCB As String
        Dim m_Baud As String
        Dim m_Parity As String
        Dim m_Data As String
        Dim m_Stop As Byte

        hPort = CreateFile(portname, GENERIC_READ + GENERIC_WRITE, _
              0, 0, OPEN_EXISTING, 0, 0)

        If hPort < 1 Then
            Throw New Exception("Can't open the comport! (Errorcode :" _
                  & GetLastError().ToString() & ")")
        End If

        m_Baud = Spd.ToString()
        m_Parity = PARITYSTRING.Substring(Pty, 1)
        m_Data = Dtb.ToString()
        m_Stop = Stp

        m_CommDCB = String.Format("baud={0} parity={1} data={2} stop={3}", _
              m_Baud, m_Parity, m_Data, m_Stop)

        BuildCommDCB(m_CommDCB, dcbPort)

        If SetCommState(hPort, dcbPort) = 0 Then
            Throw New Exception("Can't open the com port (" & _
               GetLastError().ToString() & ")")
        End If

        m_opened = True
End Sub

Thanks for the reply and the code sample, Zinnqu. In the interest of productivity I am going to stick with the .net version rather than use the Windows api.

Thanks again,
Bill

This question has already been answered. Start a new discussion instead.