Libreria Serial C#
Libreria Serial C#
System.IO.Ports
Handshake
Parity
SerialData
SerialDataReceivedEventArgs
EventType
SerialDataReceivedEventHandler
SerialError
SerialErrorReceivedEventArgs
EventType
SerialErrorReceivedEventHandler
SerialPinChange
SerialPinChangedEventArgs
EventType
SerialPinChangedEventHandler
SerialPort
BaseStream
BaudRate
BreakState
BytesToRead
BytesToWrite
CDHolding
Close
CtsHolding
DataBits
DataReceived
DiscardInBuffer
DiscardNull
DiscardOutBuffer
Dispose
DsrHolding
DtrEnable
Encoding
ErrorReceived
GetPortNames
Handshake
InfiniteTimeout
IsOpen
NewLine
Open
Parity
ParityReplace
PinChanged
PortName
Read
ReadBufferSize
ReadByte
ReadChar
ReadExisting
ReadLine
ReadTimeout
ReadTo
ReceivedBytesThreshold
RtsEnable
SerialPort
StopBits
Write
WriteBufferSize
WriteLine
WriteTimeout
StopBits
System.IO.Ports Namespace
The System.IO.Ports namespace contains classes for controlling serial ports. The most important class, SerialPort,
provides a framework for synchronous and event-driven I/O, access to pin and break states, and access to serial driver
properties. It can be used to wrap Stream objects, allowing the serial port to be accessed by classes that use streams.
Introduction
The namespace includes enumerations that simplify the control of serial ports, such as Handshake, Parity,
SerialPinChange, and StopBits.
Classes
SerialDataReceivedEventArgs
Provides data for the DataReceived event.
SerialErrorReceivedEventArgs
Prepares data for the ErrorReceived event.
SerialPinChangedEventArgs
Provides data for the PinChanged event.
SerialPort
Represents a serial port resource.
Enums
Handshake
Specifies the control protocol used in establishing a serial port
communication for a SerialPort object.
Parity
Specifies the parity bit for a SerialPort object.
SerialData
Specifies the type of character that was received on the serial
port of the SerialPort object.
SerialError
Specifies errors that occur on the SerialPort object.
SerialPinChange
Specifies the type of change that occurred on the SerialPort
object.
StopBits
Specifies the number of stop bits used on the SerialPort object.
Delegates
SerialDataReceivedEventHandler
Represents the method that will handle the DataReceived
event of a SerialPort object.
SerialErrorReceivedEventHandler
Represents the method that will handle the ErrorReceived
event of a SerialPort object.
SerialPinChangedEventHandler
Represents the method that will handle the PinChanged event
of a SerialPort object.
Handshake Handshake Enum
Specifies the control protocol used in establishing a serial port communication for a SerialPort object.
D eclaration
public enum Handshake
type Handshake =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
This enumeration is used with the Handshake property.
Fields
None None No control is used for the handshake.
RequestToSend Request-to-Send (RTS) hardware flow control is used. RTS signals that data is available for
RequestToSend transmission. If the input buffer becomes full, the RTS line will be set to false . The RTS line will
be set to true when more room becomes available in the input buffer.
RequestToSendXOnXOff Both the Request-to-Send (RTS) hardware control and the XON/XOFF software controls are used.
RequestToSendXOnXOff
XOnXOff XOnXOff The XON/XOFF software control protocol is used. The XOFF control is sent to stop the
transmission of data. The XON control is sent to resume the transmission. These software controls
are used instead of Request to Send (RTS) and Clear to Send (CTS) hardware controls.
Parity Parity Enum
Specifies the parity bit for a SerialPort object.
D eclaration
public enum Parity
type Parity =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
Use this enumeration when setting the Parity property for a serial port connection.
Parity is an error-checking procedure in which the number of 1s must always be the same - either even or odd - for
each group of bits that is transmitted without error. In modem-to-modem communications, parity is often one of the
parameters that must be agreed upon by sending parties and receiving parties before transmission can take place.
Fields
Even Even Sets the parity bit so that the count of bits set is an even number.
Odd Odd Sets the parity bit so that the count of bits set is an odd number.
D eclaration
public enum SerialData
type SerialData =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
This enumeration is used with the SerialPort.DataReceived event. You examine the type of character that was received
by retrieving the value of the SerialDataReceivedEventArgs.EventType property. The EventType property contains one
of the values from the SerialData enumeration.
Fields
Chars Chars A character was received and placed in the input buffer.
Eof Eof The end of file character was received and placed in the input buffer.
SerialDataReceivedEventArgs SerialDataReceivedEvent
Args Class
Provides data for the DataReceived event.
D eclaration
public class SerialDataReceivedEventArgs : EventArgs
type SerialDataReceivedEventArgs = class
inherit EventArgs
I nheritance H ierarchy
Object Object
EventArgs EventArgs
Remarks
This class is used with the DataReceived event.
Properties
EventType
EventType
Returns
SerialData SerialData
One of the SerialData values.
Remarks
This property provides information about the event type that caused the DataReceived event.
SerialDataReceivedEventHandler SerialDataReceived
EventHandler Delegate
Represents the method that will handle the DataReceived event of a SerialPort object.
D eclaration
public delegate void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs
e);
type SerialDataReceivedEventHandler = delegate of obj * SerialDataReceivedEventArgs -> unit
I nheritance H ierarchy
Object Object
Delegate Delegate
Remarks
When you create a SerialDataReceivedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see
Handling and Raising Events.
SerialError SerialError Enum
Specifies errors that occur on the SerialPort object.
D eclaration
public enum SerialError
type SerialError =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
This enumeration can be useful when handling the SerialPort.ErrorReceived event to detect and respond to errors
when communicating data through a SerialPort. You examine the type of error by retrieving the
SerialErrorReceivedEventArgs.EventType property. The EventType property contains one of the values from the
SerialError enumeration.
Fields
Frame Frame The hardware detected a framing error.
RXOver An input buffer overflow has occurred. There is either no room in the input buffer, or a character was
RXOver received after the end-of-file (EOF) character.
TXFull The application tried to transmit a character, but the output buffer was full.
TXFull
SerialErrorReceivedEventArgs SerialErrorReceivedEvent
Args Class
Prepares data for the ErrorReceived event.
D eclaration
public class SerialErrorReceivedEventArgs : EventArgs
type SerialErrorReceivedEventArgs = class
inherit EventArgs
I nheritance H ierarchy
Object Object
EventArgs EventArgs
Remarks
This class is used with the ErrorReceived event.
Properties
EventType
EventType
Returns
SerialError SerialError
One of the SerialError values.
Remarks
This property provides information on the event type that caused the ErrorReceived event.
SerialErrorReceivedEventHandler SerialErrorReceived
EventHandler Delegate
Represents the method that will handle the ErrorReceived event of a SerialPort object.
D eclaration
public delegate void SerialErrorReceivedEventHandler(object sender, SerialErrorReceivedEventArgs
e);
type SerialErrorReceivedEventHandler = delegate of obj * SerialErrorReceivedEventArgs -> unit
I nheritance H ierarchy
Object Object
Delegate Delegate
Remarks
When you create a SerialErrorReceivedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see
Handling and Raising Events.
SerialPinChange SerialPinChange Enum
Specifies the type of change that occurred on the SerialPort object.
D eclaration
public enum SerialPinChange
type SerialPinChange =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
This enumeration is used with the PinChanged event.
A serial port pin changes state when it is asserted or unasserted.
Fields
Break Break A break was detected on input.
CDChanged The Carrier Detect (CD) signal changed state. This signal is used to indicate whether a modem is connected
CDChanged to a working phone line and a data carrier signal is detected.
CtsChanged The Clear to Send (CTS) signal changed state. This signal is used to indicate whether data can be sent over
CtsChanged the serial port.
DsrChanged The Data Set Ready (DSR) signal changed state. This signal is used to indicate whether the device on the
DsrChanged serial port is ready to operate.
D eclaration
public class SerialPinChangedEventArgs : EventArgs
type SerialPinChangedEventArgs = class
inherit EventArgs
I nheritance H ierarchy
Object Object
EventArgs EventArgs
Remarks
This class is used with the PinChanged event.
Properties
EventType
EventType
Returns
SerialPinChange SerialPinChange
One of the SerialPinChange values.
Remarks
This property provides information about the event type that caused the PinChanged event.
SerialPinChangedEventHandler SerialPinChangedEvent
Handler Delegate
Represents the method that will handle the PinChanged event of a SerialPort object.
D eclaration
public delegate void SerialPinChangedEventHandler(object sender, SerialPinChangedEventArgs e);
type SerialPinChangedEventHandler = delegate of obj * SerialPinChangedEventArgs -> unit
I nheritance H ierarchy
Object Object
Delegate Delegate
Remarks
When you create a SerialPinChangedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see
Handling and Raising Events.
SerialPort SerialPort Class
Represents a serial port resource.
D eclaration
public class SerialPort : System.ComponentModel.Component
type SerialPort = class
inherit Component
I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
Component Component
Remarks
Use this class to control a serial port file resource. This class provides synchronous and event-driven I/O, access to pin
and break states, and access to serial driver properties. Additionally, the functionality of this class can be wrapped in an
internal Stream object, accessible through the BaseStream property, and passed to classes that wrap or use streams.
The SerialPort class supports the following encodings: ASCIIEncoding, UTF8Encoding, UnicodeEncoding,
UTF32Encoding, and any encoding defined in mscorlib.dll where the code page is less than 50000 or the code page is
54936. You can use alternate encodings, but you must use the ReadByte or Write method and perform the encoding
yourself.
You use the GetPortNames method to retrieve the valid ports for the current computer.
If a SerialPort object becomes blocked during a read operation, do not abort the thread. Instead, either close the base
stream or dispose of the SerialPort object.
Constructors
SerialPort()
SerialPort()
SerialPort(IContainer)
SerialPort(IContainer)
Initializes a new instance of the SerialPort class using the specified IContainer object.
SerialPort(String)
SerialPort(String)
Initializes a new instance of the SerialPort class using the specified port name.
SerialPort(String, Int32)
SerialPort(String, Int32)
Initializes a new instance of the SerialPort class using the specified port name and baud rate.
Initializes a new instance of the SerialPort class using the specified port name, baud rate, and parity bit.
Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, and data bits.
Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, data bits, and
stop bit.
Fields
InfiniteTimeout
InfiniteTimeout
Properties
BaseStream
BaseStream
BaudRate
BaudRate
BreakState
BreakState
BytesToRead
BytesToRead
Gets the number of bytes of data in the receive buffer.
BytesToWrite
BytesToWrite
CDHolding
CDHolding
Gets the state of the Carrier Detect line for the port.
CtsHolding
CtsHolding
DataBits
DataBits
DiscardNull
DiscardNull
Gets or sets a value indicating whether null bytes are ignored when transmitted between the port and the receive
buffer.
DsrHolding
DsrHolding
DtrEnable
DtrEnable
Gets or sets a value that enables the Data Terminal Ready (DTR ) signal during serial communication.
Encoding
Encoding
Gets or sets the byte encoding for pre- and post-transmission conversion of text.
Handshake
Handshake
Gets or sets the handshaking protocol for serial port transmission of data using a value from Handshake.
IsOpen
IsOpen
Gets a value indicating the open or closed status of the SerialPort object.
NewLine
NewLine
Gets or sets the value used to interpret the end of a call to the ReadLine() and WriteLine(String) methods.
Parity
Parity
ParityReplace
ParityReplace
Gets or sets the byte that replaces invalid bytes in a data stream when a parity error occurs.
PortName
PortName
Gets or sets the port for communications, including but not limited to all available COM ports.
ReadBufferSize
ReadBufferSize
ReadTimeout
ReadTimeout
Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.
ReceivedBytesThreshold
ReceivedBytesThreshold
Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs.
RtsEnable
RtsEnable
Gets or sets a value indicating whether the Request to Send (RTS ) signal is enabled during serial communication.
StopBits
StopBits
WriteBufferSize
WriteBufferSize
WriteTimeout
WriteTimeout
Gets or sets the number of milliseconds before a time-out occurs when a write operation does not finish.
Methods
Close()
Close()
Closes the port connection, sets the IsOpen property to false , and disposes of the internal Stream object.
DiscardInBuffer()
DiscardInBuffer()
DiscardOutBuffer()
DiscardOutBuffer()
Dispose(Boolean)
Dispose(Boolean)
Releases the unmanaged resources used by the SerialPort and optionally releases the managed resources.
GetPortNames()
GetPortNames()
Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified
offset.
Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a
given offset.
ReadByte()
ReadByte()
ReadChar()
ReadChar()
ReadExisting()
ReadExisting()
Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the
SerialPort object.
ReadLine()
ReadLine()
ReadTo(String)
ReadTo(String)
Write(String)
Write(String)
Writes the specified string to the serial port.
Writes a specified number of bytes to the serial port using data from a buffer.
Writes a specified number of characters to the serial port using data from a buffer.
WriteLine(String)
WriteLine(String)
Writes the specified string and the NewLine value to the output buffer.
Events
DataReceived
DataReceived
Indicates that data has been received through a port represented by the SerialPort object.
ErrorReceived
ErrorReceived
Indicates that an error has occurred with a port represented by a SerialPort object.
PinChanged
PinChanged
Indicates that a non-data signal event has occurred on the port represented by the SerialPort object.
SerialPort.BaseStream SerialPort.BaseStream
I n this Article
Gets the underlying Stream object for a SerialPort object.
[System.ComponentModel.Browsable(false)]
public System.IO.Stream BaseStream { get; }
member this.BaseStream : System.IO.Stream
Returns
Stream Stream
A Stream object.
Attributes BrowsableAttribute
Exceptions
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
NotSupportedException NotSupportedException
The stream is in a .NET Compact Framework application and one of the following methods was called:
BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)BeginWrite(Byte[], Int32, Int32, AsyncCallback,
Object)EndRead(IAsyncResult)EndWrite(IAsyncResult)
The .NET Compact Framework does not support the asynchronous model with base streams.
Remarks
Use this property for explicit asynchronous I/O operations or to pass the SerialPort object to a Stream wrapper class
such as StreamWriter.
Any open serial port's BaseStream property returns an object that derives from the abstract Stream class, and
implements read and write methods using the prototypes inherited from the Stream class: BeginRead, BeginWrite,
Read, ReadByte, Write, and WriteByte. These methods can be useful when passing a wrapped serial resource to a
Stream wrapper class.
Due to the inaccessibility of the wrapped file handle, the Length and Position properties are not supported, and the
Seek and SetLength methods are not supported.
SerialPort.BaudRate SerialPort.BaudRate
I n this Article
Gets or sets the serial baud rate.
[System.ComponentModel.Browsable(true)]
public int BaudRate { get; set; }
member this.BaudRate : int with get, set
Returns
Int32 Int32
The baud rate.
Attributes BrowsableAttribute
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The baud rate specified is less than or equal to zero, or is greater than the maximum allowable baud rate for the device.
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Examples
The following example shows how to set the BaudRate property to 9600 .
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
The following example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Returns
Boolean Boolean
true if the port is in a break state; otherwise, false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
The break signal state occurs when a transmission is suspended and the line is placed in a break state (all low, no stop
bit) until released. To enter a break state, set this property to true . If the port is already in a break state, setting this
property again to true does not result in an exception. It is not possible to write to the SerialPort object while
BreakState is true .
SerialPort.BytesToRead SerialPort.BytesToRead
I n this Article
Gets the number of bytes of data in the receive buffer.
[System.ComponentModel.Browsable(false)]
public int BytesToRead { get; }
member this.BytesToRead : int
Returns
Int32 Int32
The number of bytes of data in the receive buffer.
Attributes BrowsableAttribute
Exceptions
InvalidOperationException InvalidOperationException
The port is not open.
Remarks
The receive buffer includes the serial driver's receive buffer as well as internal buffering in the SerialPort object itself.
Because the BytesToRead property represents both the SerialPort buffer and the Windows-created buffer, it can return
a greater value than the ReadBufferSize property, which represents only the Windows-created buffer.
SerialPort.BytesToWrite SerialPort.BytesToWrite
I n this Article
Gets the number of bytes of data in the send buffer.
[System.ComponentModel.Browsable(false)]
public int BytesToWrite { get; }
member this.BytesToWrite : int
Returns
Int32 Int32
The number of bytes of data in the send buffer.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
The send buffer includes the serial driver's send buffer as well as internal buffering in the SerialPort object itself.
SerialPort.CDHolding SerialPort.CDHolding
I n this Article
Gets the state of the Carrier Detect line for the port.
[System.ComponentModel.Browsable(false)]
public bool CDHolding { get; }
member this.CDHolding : bool
Returns
Boolean Boolean
true if the carrier is detected; otherwise, false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
This property can be used to monitor the state of the carrier detection line for a port. No carrier usually indicates that
the receiver has hung up and the carrier has been dropped.
SerialPort.Close SerialPort.Close
I n this Article
Closes the port connection, sets the IsOpen property to false , and disposes of the internal Stream object.
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
The best practice for any application is to wait for some amount of time after calling the Close method before
attempting to call the Open method, as the port may not be closed instantly.
SerialPort.CtsHolding SerialPort.CtsHolding
I n this Article
Gets the state of the Clear-to-Send line.
[System.ComponentModel.Browsable(false)]
public bool CtsHolding { get; }
member this.CtsHolding : bool
Returns
Boolean Boolean
true if the Clear-to-Send line is detected; otherwise, false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
The Clear-to-Send (CTS ) line is used in Request to Send/Clear to Send (RTS/CTS ) hardware handshaking. The CTS line
is queried by a port before data is sent.
SerialPort.DataBits SerialPort.DataBits
I n this Article
Gets or sets the standard length of data bits per byte.
[System.ComponentModel.Browsable(true)]
public int DataBits { get; set; }
member this.DataBits : int with get, set
Returns
Int32 Int32
The data bits length.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The data bits value is less than 5 or more than 8.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Examples
This example adds a SerialDataReceivedEventHandler to DataReceived to read all the available data received on the
COM1 port. Note that to test this code it is necessary to have hardware attached to COM1 that will send data.
using System;
using System.IO.Ports;
class PortDataReceived
{
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
mySerialPort.Open();
Remarks
Data events can be caused by any of the items in the SerialData enumeration. Because the operating system
determines whether to raise this event or not, not all parity errors may be reported.
The DataReceived event is also raised if an Eof character is received, regardless of the number of bytes in the internal
input buffer and the value of the ReceivedBytesThreshold property.
PinChanged, DataReceived, and ErrorReceived events may be called out of order, and there may be a slight delay
between when the underlying stream reports the error and when the event handler is executed. Only one event
handler can execute at a time.
The DataReceived event is not guaranteed to be raised for every byte received. Use the BytesToRead property to
determine how much data is left to be read in the buffer.
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this
event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main
thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form
or Control, post change requests back using Invoke, which will do the work on the proper thread.
For more information about handling events, see Handling and Raising Events.
SerialPort.DiscardInBuffer SerialPort.DiscardInBuffer
I n this Article
Discards data from the serial driver's receive buffer.
public void DiscardInBuffer ();
member this.DiscardInBuffer : unit -> unit
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
This method is equivalent to the following Visual Basic code: MSComm1.InBufferCount = 0 . It clears the receive buffer,
but does not affect the transmit buffer.
SerialPort.DiscardNull SerialPort.DiscardNull
I n this Article
Gets or sets a value indicating whether null bytes are ignored when transmitted between the port and the receive
buffer.
[System.ComponentModel.Browsable(true)]
public bool DiscardNull { get; set; }
member this.DiscardNull : bool with get, set
Returns
Boolean Boolean
true if null bytes are ignored; otherwise false . The default is false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
This value should normally be set to false , especially for binary transmissions. Setting this property to true can
cause unexpected results for UTF32- and UTF16-encoded bytes.
SerialPort.DiscardOutBuffer SerialPort.DiscardOutBuffer
I n this Article
Discards data from the serial driver's transmit buffer.
public void DiscardOutBuffer ();
member this.DiscardOutBuffer : unit -> unit
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
This method is equivalent to the following Visual Basic code: MSComm1.OutBufferCount = 0 . It clears the transmit
buffer, but does not affect the receive buffer.
SerialPort.Dispose SerialPort.Dispose
I n this Article
Releases the unmanaged resources used by the SerialPort and optionally releases the managed resources.
protected override void Dispose (bool disposing);
override this.Dispose : bool -> unit
Parameters
disposing Boolean Boolean
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Remarks
This method is called by the public Dispose method and the Finalize method. Dispose invokes the protected Dispose
method with the disposing parameter set to true . Finalize invokes Dispose with disposing set to false .
When the disposing parameter is true , this method releases all resources held by any managed objects that this
SerialPort references. This method invokes the Dispose method of each referenced object.
This method flushes and closes the stream object in the BaseStream property.
SerialPort.DsrHolding SerialPort.DsrHolding
I n this Article
Gets the state of the Data Set Ready (DSR ) signal.
[System.ComponentModel.Browsable(false)]
public bool DsrHolding { get; }
member this.DsrHolding : bool
Returns
Boolean Boolean
true if a Data Set Ready signal has been sent to the port; otherwise, false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been
called.
Remarks
This property is used in Data Set Ready/Data Terminal Ready (DSR/DTR ) handshaking. The Data Set Ready (DSR )
signal is usually sent by a modem to a port to indicate that it is ready for data transmission or data reception.
SerialPort.DtrEnable SerialPort.DtrEnable
I n this Article
Gets or sets a value that enables the Data Terminal Ready (DTR ) signal during serial communication.
[System.ComponentModel.Browsable(true)]
public bool DtrEnable { get; set; }
member this.DtrEnable : bool with get, set
Returns
Boolean Boolean
true to enable Data Terminal Ready (DTR ); otherwise, false . The default is false .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Remarks
Data Terminal Ready (DTR ) is typically enabled during XON/XOFF software handshaking and Request to Send/Clear
to Send (RTS/CTS ) hardware handshaking, and modem communications.
SerialPort.Encoding SerialPort.Encoding
I n this Article
Gets or sets the byte encoding for pre- and post-transmission conversion of text.
[System.ComponentModel.Browsable(false)]
public System.Text.Encoding Encoding { get; set; }
member this.Encoding : System.Text.Encoding with get, set
Returns
Encoding Encoding
An Encoding object. The default is ASCIIEncoding.
Attributes BrowsableAttribute
Exceptions
ArgumentNullException ArgumentNullException
The Encoding property was set to null .
ArgumentException ArgumentException
The Encoding property was set to an encoding that is not ASCIIEncoding, UTF8Encoding, UTF32Encoding,
UnicodeEncoding, one of the Windows single byte encodings, or one of the Windows double byte encodings.
SerialPort.ErrorReceived SerialPort.ErrorReceived
I n this Article
Indicates that an error has occurred with a port represented by a SerialPort object.
public event System.IO.Ports.SerialErrorReceivedEventHandler ErrorReceived;
member this.ErrorReceived : System.IO.Ports.SerialErrorReceivedEventHandler
Remarks
Error events can be caused by any of the items in the SerialError enumeration. Because the operating system
determines whether to raise this event or not, not all parity errors may be reported.
PinChanged, DataReceived, and ErrorReceived events may be called out of order, and there may be a slight delay
between when the underlying stream reports the error and when code can when the event handler is executed. Only
one event handler can execute at a time.
If a parity error occurs on the trailing byte of a stream, an extra byte will be added to the input buffer with a value of
126.
The ErrorReceived event is raised on a secondary thread when an error is received from the SerialPort object. Because
this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main
thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form
or Control, post change requests back using Invoke, which will do the work on the proper thread.
For more information about handling events, see Handling and Raising Events.
SerialPort.GetPortNames SerialPort.GetPortNames
I n this Article
Gets an array of serial port names for the current computer.
public static string[] GetPortNames ();
static member GetPortNames : unit -> string[]
Returns
String[]
An array of serial port names for the current computer.
Exceptions
Win32Exception Win32Exception
The serial port names could not be queried.
Examples
The following code example uses the GetPortNames method to display serial port names to the console.
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class SerialPortExample
{
public static void Main()
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.ReadLine();
}
}
}
Remarks
The order of port names returned from GetPortNames is not specified.
Use the GetPortNames method to query the current computer for a list of valid serial port names. For example, you
can use this method to determine whether COM1 and COM2 are valid serial ports for the current computer.
The port names are obtained from the system registry (for example,
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM ). If the registry contains stale or otherwise
incorrect data then the GetPortNames method will return incorrect data.
SerialPort.Handshake SerialPort.Handshake
I n this Article
Gets or sets the handshaking protocol for serial port transmission of data using a value from Handshake.
[System.ComponentModel.Browsable(true)]
public System.IO.Ports.Handshake Handshake { get; set; }
member this.Handshake : System.IO.Ports.Handshake with get, set
Returns
Handshake Handshake
One of the Handshake values. The default is None .
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value passed is not a valid value in the Handshake enumeration.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Returns
Int32 Int32
Remarks
This value is used with the ReadTimeout and WriteTimeout properties.
SerialPort.IsOpen SerialPort.IsOpen
I n this Article
Gets a value indicating the open or closed status of the SerialPort object.
[System.ComponentModel.Browsable(false)]
public bool IsOpen { get; }
member this.IsOpen : bool
Returns
Boolean Boolean
true if the serial port is open; otherwise, false . The default is false .
Attributes BrowsableAttribute
Exceptions
ArgumentNullException ArgumentNullException
The IsOpen value passed is null .
ArgumentException ArgumentException
The IsOpen value passed is an empty string ("").
Remarks
The IsOpen property tracks whether the port is open for use by the caller, not whether the port is open by any
application on the machine.
SerialPort.NewLine SerialPort.NewLine
I n this Article
Gets or sets the value used to interpret the end of a call to the ReadLine() and WriteLine(String) methods.
[System.ComponentModel.Browsable(false)]
public string NewLine { get; set; }
member this.NewLine : string with get, set
Returns
String String
A value that represents the end of a line. The default is a line feed ("\n" in C# or vbLf in Visual Basic).
Attributes BrowsableAttribute
Exceptions
ArgumentException ArgumentException
The property value is empty.
ArgumentNullException ArgumentNullException
The property value is null .
Remarks
This property determines what value (byte) defines the end of a line for the ReadLine and WriteLine methods. By
default the end-of-line value is a line feed character ( \n in C#, Constants.vbLf in Visual Basic). You would change this
to a different value if the particular serial device you're working with uses a different value for the same purpose.
SerialPort.Open SerialPort.Open
I n this Article
Opens a new serial port connection.
public void Open ();
member this.Open : unit -> unit
Exceptions
UnauthorizedAccessException UnauthorizedAccessException
Access is denied to the port.
-or-
The current process, or another process on the system, already has the specified COM port open either by a SerialPort
instance or in unmanaged code.
ArgumentOutOfRangeException ArgumentOutOfRangeException
One or more of the properties for this instance are invalid. For example, the Parity, DataBits, or Handshake properties
are not valid values; the BaudRate is less than or equal to zero; the ReadTimeout or WriteTimeout property is less than
zero and is not InfiniteTimeout.
ArgumentException ArgumentException
The port name does not begin with "COM".
-or-
The file type of the port is not supported.
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
InvalidOperationException InvalidOperationException
The specified port on the current instance of the SerialPort is already open.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Returns
Parity Parity
One of the enumeration values that represents the parity-checking protocol. The default is None.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The Parity value passed is not a valid value in the Parity enumeration.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Returns
Byte Byte
A byte that replaces invalid bytes.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Remarks
If the value is set to the null character, parity replacement is disabled.
SerialPort.PinChanged SerialPort.PinChanged
I n this Article
Indicates that a non-data signal event has occurred on the port represented by the SerialPort object.
public event System.IO.Ports.SerialPinChangedEventHandler PinChanged;
member this.PinChanged : System.IO.Ports.SerialPinChangedEventHandler
Remarks
Serial pin changed events can be caused by any of the items in the SerialPinChange enumeration. Because the
operating system determines whether to raise this event or not, not all parity errors may be reported. As part of the
event, the new value of the pin is set.
The PinChanged event is raised when a SerialPort object enters the BreakState, but not when the port exits the
BreakState. This behavior does not apply to other values in the SerialPinChange enumeration.
PinChanged, DataReceived, and ErrorReceived events may be called out of order, and there may be a slight delay
between when the underlying stream reports the error and when the event handler is executed. Only one event
handler can execute at a time.
The PinChanged event is raised on a secondary thread. Because this event is raised on a secondary thread, and not the
main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading
exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke,
which will do the work on the proper thread.
For more information about handling events, see Handling and Raising Events.
SerialPort.PortName SerialPort.PortName
I n this Article
Gets or sets the port for communications, including but not limited to all available COM ports.
[System.ComponentModel.Browsable(true)]
public string PortName { get; set; }
member this.PortName : string with get, set
Returns
String String
The communications port. The default is COM1.
Attributes BrowsableAttribute
Exceptions
ArgumentException ArgumentException
The PortName property was set to a value with a length of zero.
-or-
The PortName property was set to a value that starts with "\\".
-or-
The port name was not valid.
ArgumentNullException ArgumentNullException
The PortName property was set to null .
InvalidOperationException InvalidOperationException
The specified port is open.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Overloads
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)
Reads a number of bytes from the SerialPort input buffer and
writes those bytes into a byte array at the specified offset.
Parameters
buffer Byte[]
The byte array to write the input to.
offset Int32 Int32
The offset in buffer at which to write the bytes.
count Int32 Int32
The maximum number of bytes to read. Fewer bytes are read if count is greater than the number of bytes in the input
buffer.
Returns
Int32 Int32
The number of bytes read.
Exceptions
ArgumentNullException ArgumentNullException
The buffer passed is null .
InvalidOperationException InvalidOperationException
The specified port is not open.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The offset or count parameters are outside a valid region of the buffer being passed. Either offset or count is
less than zero.
ArgumentException ArgumentException
offset plus count is greater than the length of the buffer .
TimeoutException TimeoutException
No bytes were available to read.
Remarks
If it is necessary to switch between reading text and reading binary data from the stream, select a protocol that
carefully defines the boundary between text and binary data, such as manually reading bytes and decoding the data.
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many bytes are available to read. The BytesToRead property can indicate that there are bytes
to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have
been buffered to the SerialPort class.
The Read method does not block other operations when the number of bytes read equals count but there are still
unread bytes available on the serial port.
Parameters
buffer Char[]
The character array to write the input to.
offset Int32 Int32
The offset in buffer at which to write the characters.
count Int32 Int32
The maximum number of characters to read. Fewer characters are read if count is greater than the number of
characters in the input buffer.
Returns
Int32 Int32
The number of characters read.
Exceptions
ArgumentException ArgumentException
offset plus count is greater than the length of the buffer.
-or-
count is 1 and there is a surrogate character in the buffer.
ArgumentNullException ArgumentNullException
The buffer passed is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The offset or count parameters are outside a valid region of the buffer being passed. Either offset or count is
less than zero.
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
No characters were available to read.
Remarks
Use this method for reading characters from the serial port.
If it is necessary to switch between reading text and reading binary data from the stream, select a protocol that
carefully defines the boundary between text and binary data, such as manually reading bytes and decoding the data.
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many characters are available to read. The BytesToRead property can indicate that there are
characters to read, but these characters might not be accessible to the stream contained in the BaseStream property
because they have been buffered to the SerialPort class.
The Read method does not block other operations when the number of bytes read equals count but there are still
unread bytes available on the serial port.
SerialPort.ReadBufferSize SerialPort.ReadBufferSize
I n this Article
Gets or sets the size of the SerialPort input buffer.
[System.ComponentModel.Browsable(true)]
public int ReadBufferSize { get; set; }
member this.ReadBufferSize : int with get, set
Returns
Int32 Int32
The buffer size, in bytes. The default value is 4096; the maximum value is that of a positive int, or 2147483647.
Attributes BrowsableAttribute
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The ReadBufferSize value set is less than or equal to zero.
InvalidOperationException InvalidOperationException
The ReadBufferSize property was set while the stream was open.
IOException IOException
The ReadBufferSize property was set to an odd integer value.
Remarks
The ReadBufferSize property ignores any value smaller than 4096.
Because the ReadBufferSize property represents only the Windows-created buffer, it can return a smaller value than
the BytesToRead property, which represents both the SerialPort buffer and the Windows-created buffer.
SerialPort.ReadByte SerialPort.ReadByte
I n this Article
Synchronously reads one byte from the SerialPort input buffer.
public int ReadByte ();
member this.ReadByte : unit -> int
Returns
Int32 Int32
The byte, cast to an Int32, or -1 if the end of the stream has been read.
Exceptions
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
-or-
No byte was read.
Remarks
This method reads one byte.
Use caution when using ReadByte and ReadChar together. Switching between reading bytes and reading characters
can cause extra data to be read and/or other unintended behavior. If it is necessary to switch between reading text and
reading binary data from the stream, select a protocol that carefully defines the boundary between text and binary
data, such as manually reading bytes and decoding the data.
Note
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many bytes are available to read. The BytesToRead property can indicate that there are bytes
to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have
been buffered to the SerialPort class.
SerialPort.ReadChar SerialPort.ReadChar
I n this Article
Synchronously reads one character from the SerialPort input buffer.
public int ReadChar ();
member this.ReadChar : unit -> int
Returns
Int32 Int32
The character that was read.
Exceptions
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
-or-
No character was available in the allotted time-out period.
Remarks
This method reads one complete character based on the encoding.
Use caution when using ReadByte and ReadChar together. Switching between reading bytes and reading characters
can cause extra data to be read and/or other unintended behavior. If it is necessary to switch between reading text and
reading binary data from the stream, select a protocol that carefully defines the boundary between text and binary
data, such as manually reading bytes and decoding the data.
Note
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many bytes are available to read. The BytesToRead property can indicate that there are bytes
to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have
been buffered to the SerialPort class.
SerialPort.ReadExisting SerialPort.ReadExisting
I n this Article
Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort
object.
Returns
String String
The contents of the stream and the input buffer of the SerialPort object.
Exceptions
InvalidOperationException InvalidOperationException
The specified port is not open.
Remarks
This method returns the contents of the stream and internal buffer of the SerialPort object as a string. This method
does not use a time-out. Note that this method can leave trailing lead bytes in the internal buffer, which makes the
BytesToRead value greater than zero.
If it is necessary to switch between reading text and reading binary data from the stream, select a protocol that
carefully defines the boundary between text and binary data, such as manually reading bytes and decoding the data.
Note
The SerialPort class buffers data, but the stream object contained in the SerialPort.BaseStream property does not.
Therefore, the SerialPort object and the stream object might differ on the number of bytes that are available to read.
When bytes are buffered to the SerialPort object, the BytesToRead property includes these bytes in its value; however,
these bytes might not be accessible to the stream contained in the BaseStream property.
SerialPort.ReadLine SerialPort.ReadLine
I n this Article
Reads up to the NewLine value in the input buffer.
public string ReadLine ();
member this.ReadLine : unit -> string
Returns
String String
The contents of the input buffer up to the first occurrence of a NewLine value.
Exceptions
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
-or-
No bytes were read.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. This code example is part of a larger code example provided for the
SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many bytes are available to read. The BytesToRead property can indicate that there are bytes
to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have
been buffered to the SerialPort class.
SerialPort.ReadTimeout SerialPort.ReadTimeout
I n this Article
Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.
[System.ComponentModel.Browsable(true)]
public int ReadTimeout { get; set; }
member this.ReadTimeout : int with get, set
Returns
Int32 Int32
The number of milliseconds before a time-out occurs when a read operation does not finish.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The read time-out value is less than zero and not equal to InfiniteTimeout.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Users of the unmanaged COMMTIMEOUTS structure might expect to set the time-out value to zero to suppress time-outs.
To suppress time-outs with the ReadTimeout property, however, you must specify InfiniteTimeout.
This property does not affect the BeginRead method of the stream returned by the BaseStream property.
SerialPort.ReadTo SerialPort.ReadTo
I n this Article
Reads a string up to the specified value in the input buffer.
Parameters
value String String
A value that indicates where the read operation stops.
Returns
String String
The contents of the input buffer up to the specified value .
Exceptions
ArgumentException ArgumentException
The length of the value parameter is 0.
ArgumentNullException ArgumentNullException
The value parameter is null .
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
Remarks
This method reads a string up to the specified value . While the returned string does not include the value , the value
is removed from the input buffer.
If it is necessary to switch between reading text and reading binary data from the stream, select a protocol that
carefully defines the boundary between text and binary data, such as manually reading bytes and decoding the data.
Note
Because the SerialPort class buffers data, and the stream contained in the BaseStream property does not, the two
might conflict about how many bytes are available to read. The BytesToRead property can indicate that there are bytes
to read, but these bytes might not be accessible to the stream contained in the BaseStream property because they have
been buffered to the SerialPort class.
SerialPort.ReceivedBytesThreshold SerialPort.Received
BytesThreshold
I n this Article
Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs.
[System.ComponentModel.Browsable(true)]
public int ReceivedBytesThreshold { get; set; }
member this.ReceivedBytesThreshold : int with get, set
Returns
Int32 Int32
The number of bytes in the internal input buffer before a DataReceived event is fired. The default is 1.
Attributes BrowsableAttribute
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The ReceivedBytesThreshold value is less than or equal to zero.
Remarks
The DataReceived event is also raised if an Eof character is received, regardless of the number of bytes in the internal
input buffer and the value of the ReceivedBytesThreshold property.
SerialPort.RtsEnable SerialPort.RtsEnable
I n this Article
Gets or sets a value indicating whether the Request to Send (RTS ) signal is enabled during serial communication.
[System.ComponentModel.Browsable(true)]
public bool RtsEnable { get; set; }
member this.RtsEnable : bool with get, set
Returns
Boolean Boolean
true to enable Request to Transmit (RTS ); otherwise, false . The default is false .
Attributes BrowsableAttribute
Exceptions
InvalidOperationException InvalidOperationException
The value of the RtsEnable property was set or retrieved while the Handshake property is set to the RequestToSend
value or the RequestToSendXOnXOff value.
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Remarks
The Request to Transmit (RTS ) signal is typically used in Request to Send/Clear to Send (RTS/CTS ) hardware
handshaking.
SerialPort SerialPort
I n this Article
Overloads
SerialPort()
Initializes a new instance of the SerialPort class.
SerialPort(IContainer) SerialPort(IContainer)
Initializes a new instance of the SerialPort class using the
specified IContainer object.
SerialPort(String) SerialPort(String)
Initializes a new instance of the SerialPort class using the
specified port name.
SerialPort()
Initializes a new instance of the SerialPort class.
public SerialPort ();
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Remarks
This constructor uses default property values when none are specified. For example, the DataBits property defaults to
8, the Parity property defaults to the None enumeration value, the StopBits property defaults to 1, and a default port
name of COM1.
SerialPort(IContainer) SerialPort(IContainer)
Initializes a new instance of the SerialPort class using the specified IContainer object.
Parameters
container IContainer IContainer
An interface to a container.
Exceptions
IOException IOException
The specified port could not be found or opened.
Remarks
This constructor uses default property values when none are specified. For example, the DataBits property defaults to
8, the Parity property defaults to the None enumeration value, the StopBits property defaults to 1, and a default port
name of COM1.
SerialPort(String) SerialPort(String)
Initializes a new instance of the SerialPort class using the specified port name.
public SerialPort (string portName);
new System.IO.Ports.SerialPort : string -> System.IO.Ports.SerialPort
Parameters
portName String String
The port to use (for example, COM1).
Exceptions
IOException IOException
The specified port could not be found or opened.
Remarks
Use this constructor to create a new instance of the SerialPort class when you want to specify the port name.
Parameters
portName String String
The port to use (for example, COM1).
baudRate Int32 Int32
The baud rate.
parity Parity Parity
One of the Parity values.
Exceptions
IOException IOException
The specified port could not be found or opened.
Remarks
Use this constructor to create a new instance of the SerialPort class when you want to specify the port name, the baud
rate, and the parity bit.
public SerialPort (string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits);
new System.IO.Ports.SerialPort : string * int * System.IO.Ports.Parity * int ->
System.IO.Ports.SerialPort
Parameters
portName String String
The port to use (for example, COM1).
baudRate Int32 Int32
The baud rate.
parity Parity Parity
One of the Parity values.
dataBits Int32 Int32
The data bits value.
Exceptions
IOException IOException
The specified port could not be found or opened.
Remarks
Use this constructor to create a new instance of the SerialPort class when you want to specify the port name, the baud
rate, the parity bit, and data bits.
public SerialPort (string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits,
System.IO.Ports.StopBits stopBits);
new System.IO.Ports.SerialPort : string * int * System.IO.Ports.Parity * int *
System.IO.Ports.StopBits -> System.IO.Ports.SerialPort
Parameters
portName String String
The port to use (for example, COM1).
baudRate Int32 Int32
The baud rate.
parity Parity Parity
One of the Parity values.
dataBits Int32 Int32
The data bits value.
stopBits StopBits StopBits
One of the StopBits values.
Exceptions
IOException IOException
The specified port could not be found or opened.
Remarks
Use this constructor to create a new instance of the SerialPort class when you want to specify the port name, the baud
rate, the parity bit, data bits, and stop bit.
SerialPort.StopBits SerialPort.StopBits
I n this Article
Gets or sets the standard number of stopbits per byte.
[System.ComponentModel.Browsable(true)]
public System.IO.Ports.StopBits StopBits { get; set; }
member this.StopBits : System.IO.Ports.StopBits with get, set
Returns
StopBits StopBits
One of the StopBits values.
Attributes BrowsableAttribute
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The StopBits value is None.
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
Examples
The following example shows how to set the StopBits property to One .
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true;
The following example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Overloads
Write(String) Write(String)
Writes the specified string to the serial port.
Write(String) Write(String)
Writes the specified string to the serial port.
public void Write (string str);
member this.Write : string -> unit
Parameters
text String String
The string for output.
Exceptions
InvalidOperationException InvalidOperationException
The specified port is not open.
ArgumentNullException ArgumentNullException
text is null .
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
Remarks
Use this method when you want to write a string as output to a serial port.
If there are too many bytes in the output buffer and Handshake is set to XOnXOff then the SerialPort object may raise
a TimeoutException while it waits for the device to be ready to accept more data.
By default, SerialPort uses ASCIIEncoding to encode the characters. ASCIIEncoding encodes all characters greater than
127 as (char)63 or '?'. To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding,
or UnicodeEncoding.
Parameters
buffer Byte[]
The byte array that contains the data to write to the port.
offset Int32 Int32
The zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.
count Int32 Int32
The number of bytes to write.
Exceptions
ArgumentNullException ArgumentNullException
The buffer passed is null .
InvalidOperationException InvalidOperationException
The specified port is not open.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The offset or count parameters are outside a valid region of the buffer being passed. Either offset or count is
less than zero.
ArgumentException ArgumentException
offset plus count is greater than the length of the buffer .
TimeoutException TimeoutException
The operation did not complete before the time-out period ended.
Remarks
Use this method when you want to write to a byte buffer to create output to a serial port.
If there are too many bytes in the output buffer and Handshake is set to XOnXOff then the SerialPort object may raise
a TimeoutException while it waits for the device to be ready to accept more data.
By default, SerialPort uses ASCIIEncoding to encode the characters. ASCIIEncoding encodes all characters greater than
127 as (char)63 or '?'. To support additional characters in that range, set Encoding to UTF8Encoding, UTF32Encoding,
or UnicodeEncoding.
Parameters
buffer Char[]
The character array that contains the data to write to the port.
offset Int32 Int32
The zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.
Returns
Int32 Int32
The size of the output buffer. The default is 2048.
Attributes BrowsableAttribute
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The WriteBufferSize value is less than or equal to zero.
InvalidOperationException InvalidOperationException
The WriteBufferSize property was set while the stream was open.
IOException IOException
The WriteBufferSize property was set to an odd integer value.
Remarks
The WriteBufferSize property ignores any value smaller than 2048.
SerialPort.WriteLine SerialPort.WriteLine
I n this Article
Writes the specified string and the NewLine value to the output buffer.
public void WriteLine (string str);
member this.WriteLine : string -> unit
Parameters
text String String
The string to write to the output buffer.
Exceptions
ArgumentNullException ArgumentNullException
The text parameter is null .
InvalidOperationException InvalidOperationException
The specified port is not open.
TimeoutException TimeoutException
The WriteLine(String) method could not write to the stream.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. This code example is part of a larger code example provided for the
SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Returns
Int32 Int32
The number of milliseconds before a time-out occurs. The default is InfiniteTimeout.
Attributes BrowsableAttribute
Exceptions
IOException IOException
The port is in an invalid state.
-or-
An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort
object were invalid.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The WriteTimeout value is less than zero and not equal to InfiniteTimeout.
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate
computers connected by a null modem cable. In this example, the users are prompted for the port settings and a
username before chatting. This code example is part of a larger code example provided for the SerialPort class.
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
Users of the unmanaged COMMTIMEOUTS structure might expect to set the time-out value to zero to suppress time-outs.
To suppress time-outs with the WriteTimeout property, however, you must specify InfiniteTimeout.
This property does not affect the BeginWrite method of the stream returned by the BaseStream property.
StopBits StopBits Enum
Specifies the number of stop bits used on the SerialPort object.
D eclaration
public enum StopBits
type StopBits =
I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum
Remarks
You use this enumeration when setting the value of the StopBits property on the SerialPort class. Stop bits separate
each unit of data on an asynchronous serial connection. They are also sent continuously when no data is available for
transmission.
The SerialPort class throws an ArgumentOutOfRangeException exception when you set the StopBits property to None.
Fields
None None No stop bits are used. This value is not supported by the StopBits property.