The serial port behaves as a stream, but before you can read and write from the stream you must define the Serial Port Properties and open it.


Once you've configured the serial port, you issue the Open method.

SerialPortStream s = new SerialPortStream("COM1", 115200, 8, Parity.None, StopBits.One);

When the serial port is opened, it begins a background thread to read data from the serial port into the read buffer. Writing to the serial port is now allowed.

Retrieving the Windows state

You might want to open the port and observe the configuration last set by Windows. The method {GetPortSettings() does this for you.

It will overwrite the properties of the object with that returned by Windows. The DCB structure is checked for consistency and corrected.

SerialPortStream s = new SerialPortStream();
s.PortName = "COM1";


You can use the property IsOpen to know if the serial port is already opened.


Once you've finished working with the serial port you can Close it. Closing the serial port closes the handle associated with the driver and stops the I/O thread running in the background. You can no longer Write to the serial port and the write buffer is flushed.

Read will still continue to work, returning the data remaining in the read buffer that hasn't yet been read.


After closing the serial port, you may reopen it. The Read buffer remains, so if you expect to have no data, you'll have to call DiscardInBuffer before reopening the serial port.


Disposing the SerialPortStream will also close the serial port if it is currently open. Disposing the SerialPortStream disallows it from being opened again in the future. All internal handles are cleaned up.

It is recommended that when you're finished using the serial port that you call Dispose.


The property IsDisposed allows you to check if the object has been disposed or not. If the object has been disposed, you cannot (and should not) do anything with the object. Pinned memory has been freed and resources have been returned to the Operating System.

Last edited Sep 24, 2012 at 8:15 PM by jmcurl, version 5


No comments yet.