SerialPort Class

SerialPort Class

Represents a serial port resource.

Namespace: System.IO.Ports
Assembly: System (in system.dll)

Public Class SerialPort
	Inherits Component
Dim instance As SerialPort

public class SerialPort extends Component
public class SerialPort extends Component
Not applicable.

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.

Imports System
Imports System.IO.Ports
Imports System.Threading

Public Class PortChat
    Shared _continue As Boolean
    Shared _serialPort As SerialPort

    Public Shared Sub Main()
        Dim name As String
        Dim message As String
        Dim sComparer As StringComparer = StringComparer.OrdinalIgnoreCase
        Dim readThread As Thread = New Thread(AddressOf 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

        _continue = True

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

        Console.WriteLine("Type QUIT to exit")

        While (_continue)
            message = Console.ReadLine()

            If sComparer.Equals("quit", message) Then
                _continue = False
                _serialPort.WriteLine( _
                    String.Format("<{0}>: {1}", name, message))
            End If
        end while

    End Sub

    Public Shared Sub Read()
        While (_continue)
                Dim message As String = _serialPort.ReadLine()
            Catch ex As TimeoutException
                ' Do nothing
            End Try
        End While
    End Sub

    Public Shared Function SetPortName(ByVal defaultPortName As String) As String
        Dim newPortName As String

        Console.WriteLine("Available Ports:")
        Dim s As String
        For Each s In SerialPort.GetPortNames()
            Console.WriteLine("   {0}", s)
        Next s

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

        If newPortName = "" Then
            newPortName = defaultPortName
        End If
        Return newPortName
    End Function

    Public Shared Function SetPortBaudRate(ByVal defaultPortBaudRate As Integer) As Integer
        Dim newBaudRate As String

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

        If newBaudRate = "" Then
            newBaudRate = defaultPortBaudRate.ToString()
        End If

        Return Integer.Parse(newBaudRate)
    End Function

    Public Shared Function SetPortParity(ByVal defaultPortParity As Parity) As Parity
        Dim newParity As String

        Console.WriteLine("Available Parity options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(Parity))
            Console.WriteLine("   {0}", s)
        Next s

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

        If newparity = "" Then
            newparity = defaultPortParity.ToString()
        End If

        Return CType([Enum].Parse(GetType(Parity), newParity), Parity)
    End Function

    Public Shared Function SetPortDataBits(ByVal defaultPortDataBits As Integer) As Integer
        Dim newDataBits As String

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

        If newDataBits = "" Then
            newDataBits = defaultPortDataBits.ToString()
        End If

        Return Integer.Parse(newDataBits)
    End Function

    Public Shared Function SetPortStopBits(ByVal defaultPortStopBits As StopBits) As StopBits
        Dim newStopBits As String

        Console.WriteLine("Available Stop Bits options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(StopBits))
            Console.WriteLine("   {0}", s)
        Next s

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

        If newStopBits = "" Then
            newStopBits = defaultPortStopBits.ToString()
        End If

        Return CType([Enum].Parse(GetType(StopBits), newStopBits), StopBits)
    End Function

    Public Shared Function SetPortHandshake(ByVal defaultPortHandshake As Handshake) As Handshake
        Dim newHandshake As String

        Console.WriteLine("Available Handshake options:")
        Dim s As String
        For Each s In [Enum].GetNames(GetType(Handshake))
            Console.WriteLine("   {0}", s)
        Next s

        Console.Write("Stop Bits({0}):", defaultPortHandshake.ToString())
        newHandshake = Console.ReadLine()

        If newHandshake = "" Then
            newHandshake = defaultPortHandshake.ToString()
        End If

        Return CType([Enum].Parse(GetType(Handshake), newHandshake), Handshake)
    End Function
End Class

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 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

.NET Compact Framework

Supported in: 2.0

Community Additions

© 2016 Microsoft