65.9K
CodeProject is changing. Read more.
Home

Read n bytes from the serial port in .NET

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Mar 6, 2012

CPOL
viewsIcon

52113

Read n bytes from the serial port in .net

Introduction

This code snippet tries to help you to read n bytes from the Serial Port in .NET Framework.

Background

Working with the serial port in .NET, I found what appears to be a fairly common problem:

SerialPort.Read(buffer,offset,length)

The above code doesn't return the bytes requested, instead, return the bytes available in buffer and you need to call this function repeatedly in order to obtain the required bytes.

Solution

Based in this post I make my own solution with a Extension Method:

<Extension()>
Public Function Read(ByVal port As SerialPort, ByVal count As Integer) As Byte()
 Dim buffer(count - 1) As Byte
 Dim readBytes As Integer
 Dim totalReadBytes As Integer
 Dim offset As Integer
 Dim remaining As Integer = count
 
 Try
    Do
       readBytes = port.Read(buffer, offset, remaining)
       offset += readBytes
       remaining -= readBytes
       totalReadBytes += readBytes
    Loop While remaining > 0 AndAlso readBytes > 0
 Catch ex As TimeoutException
    ReDim Preserve buffer(totalReadBytes - 1)
 End Try
 
 Return buffer
 
End Function

The above function loops until all bytes requested are read. If a TimeOutException occurs (because there are no more data in buffer), the fuction returns the bytes read until the exception occured or a empty byte array if no byte was read.

I hope this can help or if any of you have a better option let us know.

Write your comments, thanks.

Read n bytes from the serial port in .NET - CodeProject