Using .NET’s SerialPort Class
An alternate way to close a port is with a Using block. On exiting the Using
block, the SerialPort object named in the Using statement is closed automati-
cally and its resources are disposed of:
Using myComPort As New SerialPort
myComPort.PortName = "COM6"
myComPort.BaudRate = 115200
myComPort.Open()
myComPort.WriteLine("hello")
End Using
using (SerialPort myComPort = new SerialPort())
{
myComPort.PortName = "COM6";
myComPort.BaudRate = 115200;
myComPort.Open();
myComPort.WriteLine("hello");
}
Closing a port can take up to a few seconds (or longer if waiting for the port to
finish transmitting), so applications and users should delay a bit between clos-
ing a port and re-opening the same port.
!
The .NET Framework supports many methods for reading and writing to
COM ports. An application that sends a text command and waits for a response
will likely use a different method than an application that is sending a large file
of object code.
The SerialPort class provides methods for reading and writing to ports. Applica-
tions can also use a SerialPort object’s BaseStream property to obtain Bina-
ryReader, BinaryWriter, StreamReader, and StreamWriter objects and use their
methods to access a port. Table 9-1 and Table 9-2 summarize methods for read-
ing and writing to SerialPort objects.
A basic data type for COM-port data is the byte array. An application can trans-
fer any kind of data in byte arrays. The COM-port software makes no assump-
tions about the meaning of the data or how the receiving computer will use the
data. An application can encode data before placing it in a byte array and writ-
ing the array to the port. The receiving computer can decode the received data
as needed.