using System;
using System.IO;
using System.Text;
namespace CUP_POD_Mail_Reader.Common
{
///
/// Utility to help reading bytes and strings of a
///
internal static class StreamUtility
{
///
/// Read a line from the stream.
/// A line is interpreted as all the bytes read until a CRLF or LF is encountered.
/// CRLF pair or LF is not included in the string.
///
/// The stream from which the line is to be read
/// A line read from the stream returned as a byte array or if no bytes were readable from the stream
/// If is
public static byte[] ReadLineAsBytes(Stream stream)
{
if(stream == null)
throw new ArgumentNullException("stream");
using (MemoryStream memoryStream = new MemoryStream())
{
while (true)
{
int justRead = stream.ReadByte();
if (justRead == -1 && memoryStream.Length > 0)
break;
// Check if we started at the end of the stream we read from
// and we have not read anything from it yet
if (justRead == -1 && memoryStream.Length == 0)
return null;
char readChar = (char)justRead;
// Do not write \r or \n
if (readChar != '\r' && readChar != '\n')
memoryStream.WriteByte((byte)justRead);
// Last point in CRLF pair
if (readChar == '\n')
break;
}
return memoryStream.ToArray();
}
}
///
/// Read a line from the stream. for more documentation.
///
/// The stream to read from
/// A line read from the stream or if nothing could be read from the stream
/// If is
public static string ReadLineAsAscii(Stream stream)
{
byte[] readFromStream = ReadLineAsBytes(stream);
return readFromStream != null ? Encoding.ASCII.GetString(readFromStream) : null;
}
}
}