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