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


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: