66 out of 109 rated this helpful - Rate this topic

SerialPort Class

Represents a serial port resource.

Namespace:  System.IO.Ports
Assembly:  System (in System.dll)
public class SerialPort : Component

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.

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. Both computers must be executing the program to achieve full functionality of this example.

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        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();
    }

    public static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("COM port({0}): ", defaultPortName);
        portName = Console.ReadLine();

        if (portName == "")
        {
            portName = defaultPortName;
        }
        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Parity({0}):", defaultPortParity.ToString());
        parity = Console.ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        Console.Write("Data Bits({0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        Console.WriteLine("Available Stop Bits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();

        if (stopBits == "")
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Handshake({0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Read Buffer threshold Insane Delay
Hey im streaming 32 characters of information from my Atmega324 and in hyperterminal changes in, say my encoders is updated immediately.

But when i use the system.io.ports (.net 2 serial) i get atleast 6 seconds delay before i see a change!!!!!!! >> Im reading in buffer till i see new line and even after tinkering with timeouts, buffersizes and thresholds im still getting crazy lag!!!


Ive had to currently revert to using MSCOMM32.OCX to get nice and fast input from my serial. . . . <<This is what really confuses me. . how does an older implementation work so much better???

PLEASE HELP!!!!
Yes this example is thread safe w/o locking
Notice the serial port used in this example is static, which according to their documentation is thread-safe. If it was an instance locking would probably be required. Does anyone know the advantage of this looping thread approach vs. using a DataReceived event handler.
Serialport
I'm trying to read the serial port in Visual Basic using serialport1.readline function. It's really frustrating, since I can't get anything read back. If I use Hyperterm (copied in Vista from XP) I can see all the characters coming in. The connection is 9600baud, 7bits/char, odd parity, 2 stop bits. Am I missing something here, since it's obvious the problem is with Visual Basic 2008 express edition? Sending data is fine.

Mihai
SerialPort.Read returns zero, even when reading bytes
I'm trying to read from the COM port using:

BytesRead = COM.Read(RXBuffer, BytesRead, BytesExpected - BytesRead)

But Im observing behaviour which is inconsistent with MSDN documentation. The read operation obviously completes successfully (RXBuffer indeed contains all the data that was expected), yet BytesRead remains at zero value.

Can anyone provide some insight, as to what I am doing wrong? please?
SerialPort bug?
If you plug out the cable after connecting using serialport,there is a severe memory leakage problem.

Please email me to "uniquegodwin at gmail.com" if anyone has the solution.
Thanks.
Why is the Read method not a blocking method?

internal void recieveMessage(ref Message message, int length)
{
lock (_serialPort)
{
// This method may return more message bytes than specified in the length.

int numberOfBytesRead = 0;
byte[] readBuffer = new byte[length];

numberOfBytesRead = _serialPort.Read(readBuffer, 0, length);

// Force a read (if any data exists) to clear the buffer of any garbage data
if (_serialPort.BytesToRead > 0)
{
_serialPort.ReadExisting();
}
// Parse the message
message = message.Parse(readBuffer);
}
}

Typo in SetPortHandshake()

I suppose the string "Stop Bits({0}):" in SetPortHandshake() is a typo as the method wants input for a handshake method and not stop bits.

This goes for both C# and Visual Basic examples.

Console.Write("Stop Bits({0}):", defaultPortHandshake.ToString());

Two threads accessing the serial port at the same time without locking?

Is this example thread safe? Shouldn't there be a lock object used to ensure that only either the read thread or the write thread use the serial port at the same time? Or is this generally safe to do without locking?

And shouldn't the read thread sit idle until some event like the DataReceived is triggered rather than a tight loop around ReadLine?