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





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: