StreamUtility.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace CUP_POD_Mail_Reader.Common
  5. {
  6. /// <summary>
  7. /// Utility to help reading bytes and strings of a <see cref="Stream"/>
  8. /// </summary>
  9. internal static class StreamUtility
  10. {
  11. /// <summary>
  12. /// Read a line from the stream.
  13. /// A line is interpreted as all the bytes read until a CRLF or LF is encountered.<br/>
  14. /// CRLF pair or LF is not included in the string.
  15. /// </summary>
  16. /// <param name="stream">The stream from which the line is to be read</param>
  17. /// <returns>A line read from the stream returned as a byte array or <see langword="null"/> if no bytes were readable from the stream</returns>
  18. /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <see langword="null"/></exception>
  19. public static byte[] ReadLineAsBytes(Stream stream)
  20. {
  21. if(stream == null)
  22. throw new ArgumentNullException("stream");
  23. using (MemoryStream memoryStream = new MemoryStream())
  24. {
  25. while (true)
  26. {
  27. int justRead = stream.ReadByte();
  28. if (justRead == -1 && memoryStream.Length > 0)
  29. break;
  30. // Check if we started at the end of the stream we read from
  31. // and we have not read anything from it yet
  32. if (justRead == -1 && memoryStream.Length == 0)
  33. return null;
  34. char readChar = (char)justRead;
  35. // Do not write \r or \n
  36. if (readChar != '\r' && readChar != '\n')
  37. memoryStream.WriteByte((byte)justRead);
  38. // Last point in CRLF pair
  39. if (readChar == '\n')
  40. break;
  41. }
  42. return memoryStream.ToArray();
  43. }
  44. }
  45. /// <summary>
  46. /// Read a line from the stream. <see cref="ReadLineAsBytes"/> for more documentation.
  47. /// </summary>
  48. /// <param name="stream">The stream to read from</param>
  49. /// <returns>A line read from the stream or <see langword="null"/> if nothing could be read from the stream</returns>
  50. /// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <see langword="null"/></exception>
  51. public static string ReadLineAsAscii(Stream stream)
  52. {
  53. byte[] readFromStream = ReadLineAsBytes(stream);
  54. return readFromStream != null ? Encoding.ASCII.GetString(readFromStream) : null;
  55. }
  56. }
  57. }