Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LineReader : IDisposable
- {
- private Stream stream;
- private BinaryReader reader;
- public LineReader(Stream stream) { reader = new BinaryReader(stream); }
- public string ReadLine()
- {
- StringBuilder result = new StringBuilder();
- char lastChar = reader.ReadChar();
- // an EndOfStreamException here would propogate to the caller
- try
- {
- char newChar = reader.ReadChar();
- if (lastChar == 'r' && newChar == 'n')
- return result.ToString();
- result.Append(lastChar);
- lastChar = newChar;
- }
- catch (EndOfStreamException)
- {
- result.Append(lastChar);
- return result.ToString();
- }
- }
- public void Dispose()
- {
- reader.Close();
- }
- }
- 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;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement