Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#

ReadLine on Binary Stream

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 Mar 2012CPOL 47.4K   6   9
ReadLine on Binary Stream

When you are reading data from a binary stream, like NetworkStream or FileStream and you need to read both binary chunks as well as read one text line at a time, you are on your own as neither BinaryReader nor Stream supports ReadLine. You can use StreamReader to do ReadLine, but it does not allow you to read chunks of bytes. The Read(byte[], int, int) is not there on StreamReader.

Here’s an extension of BinaryReader for doing ReadLine over a binary stream. You can read both byte chunks, as well as read text lines at the same time.

C#
public class LineReader : BinaryReader
{
  private Encoding _encoding;
  private Decoder _decoder;

  const int bufferSize = 1024;
  private char[] _LineBuffer = new char[bufferSize];
    
  public LineReader(Stream stream, int bufferSize, Encoding encoding)
    : base(stream, encoding)
  {
    this._encoding = encoding;
    this._decoder = encoding.GetDecoder();
  }

  public string ReadLine()
  {
    int pos = 0;
    
    char[] buf = new char[2];

    StringBuilder stringBuffer = null;
    bool lineEndFound = false;

    while(base.Read(buf, 0, 2) > 0)
    {
      if (buf[1] == '\r')
      {
        // grab buf[0]
        this._LineBuffer[pos++] = buf[0];
        // get the '\n'
        char ch = base.ReadChar();
        Debug.Assert(ch == '\n');

        lineEndFound = true;
      }
      else if (buf[0] == '\r')
      {
        lineEndFound = true;
      }          
      else
      {
        this._LineBuffer[pos] = buf[0];
        this._LineBuffer[pos+1] = buf[1];
        pos += 2;

        if (pos >= bufferSize)
        {
          stringBuffer = new StringBuilder(bufferSize + 80);
          stringBuffer.Append(this._LineBuffer, 0, bufferSize);
          pos = 0;
        }
      }

      if (lineEndFound)
      {
        if (stringBuffer == null)
        {
          if (pos > 0)
            return new string(this._LineBuffer, 0, pos);
          else
            return string.Empty;
        }
        else
        {
          if (pos > 0)
            stringBuffer.Append(this._LineBuffer, 0, pos);
          return stringBuffer.ToString();
        }
      }
    }

    if (stringBuffer != null)
    {
      if (pos > 0)
        stringBuffer.Append(this._LineBuffer, 0, pos);
      return stringBuffer.ToString();
    }
    else
    {
      if (pos > 0)
        return new string(this._LineBuffer, 0, pos);
      else
        return null;
    }
  }
}

Enjoy!

License

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


Written By
Architect BT, UK (ex British Telecom)
United Kingdom United Kingdom

Comments and Discussions

 
QuestionHas the tech moved on? Pin
pekatete28-Apr-21 2:26
pekatete28-Apr-21 2:26 
QuestionThere are a few caveats.. Pin
jfriedman29-Jan-15 14:41
jfriedman29-Jan-15 14:41 
AnswerRe: There are a few caveats.. Pin
jfriedman29-Jan-15 14:41
jfriedman29-Jan-15 14:41 
GeneralRe: There are a few caveats.. Pin
jfriedman29-Jan-15 14:42
jfriedman29-Jan-15 14:42 
AnswerRe: There are a few caveats.. Pin
Ansgar Hellwig23-Mar-17 22:52
professionalAnsgar Hellwig23-Mar-17 22:52 
GeneralMy vote of 4 Pin
NinjaCross12-Jul-13 14:02
NinjaCross12-Jul-13 14:02 
QuestionStreamReader and BinaryReader Pin
Ron Beyer2-Mar-12 16:54
professionalRon Beyer2-Mar-12 16:54 
AnswerRe: StreamReader and BinaryReader Pin
Omar Al Zabir3-Mar-12 7:59
Omar Al Zabir3-Mar-12 7:59 
GeneralRe: StreamReader and BinaryReader Pin
David Latheron18-Aug-15 7:02
David Latheron18-Aug-15 7:02 

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.