Access a COM port in .NET

To access a COM port in .NET, just use the SerialPort class, which represents a serial port resource. Here’s how to access the COM ports on your computer and list some of its properties

C#

static void Main(string[] args)
{
// Retrieve a list of serial port names.
string[] ports = SerialPort.GetPortNames();

Console.WriteLine("List of Serial ports on your machine:");

// Display each port name to the console.
foreach (string sPort in ports)
{
using (SerialPort port = new SerialPort(sPort))
{
Console.WriteLine("BaudRate : " + port.BaudRate);
Console.WriteLine("ReadTimeout : " + port.ReadTimeout);
// Send a message to the port
port.Open();
port.Write("Hello Port!");
}
}

Console.ReadLine();
}

VB.NET (Converted Code)

Sub Main()
' Retrieve a list of serial port names.
Dim ports() As String = SerialPort.GetPortNames()

Console.WriteLine("List of Serial ports on your machine:")

' Display each port name to the console.
For Each sPort As String In ports
Using port As New SerialPort(sPort)
Console.WriteLine("BaudRate : " & port.BaudRate)
Console.WriteLine("ReadTimeout : " & port.ReadTimeout)
' Send a message to the port
port.Open()
port.Write("Hello Port!")
End Using
Next
sPort

Console.ReadLine()
End Sub

No comments:

Post a Comment