Click here to Skip to main content
13,146,934 members (69,368 online)
Click here to Skip to main content
Add your own
alternative version


4 bookmarked
Posted 6 Mar 2012

Read n bytes from the serial port in .NET

, 6 Mar 2012
Rate this:
Please Sign up or sign in to vote.
Read n bytes from the serial port in .net


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


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


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.


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

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
       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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mexico Mexico
No Biography provided

You may also be interested in...


Comments and Discussions

PraiseNice Solution Pin
bojammis18-Feb-16 8:11
professionalbojammis18-Feb-16 8:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170915.1 | Last Updated 6 Mar 2012
Article Copyright 2012 by cass3000
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid