staafl

TextReaderWithNewlines

May 21st, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. using System.IO;
  2. using System.Text;
  3.  
  4. class TextReaderWithNewlines : TextReader
  5. {
  6. public TextReaderWithNewlines(TextReader inner)
  7. {
  8. this.tr = inner;
  9. }
  10.  
  11. readonly TextReader tr;
  12. readonly StringBuilder buffer = new StringBuilder();
  13.  
  14. string ReturnAndEmpty()
  15. {
  16. var ret = buffer.ToString();
  17. buffer.Length = 0;
  18. return ret;
  19. }
  20.  
  21. public override string ReadLine()
  22. {
  23. while (true)
  24. {
  25. var as_read = tr.Read();
  26.  
  27. if (as_read == -1)
  28. {
  29. if (buffer.Length == 0)
  30. return null;
  31. return ReturnAndEmpty();
  32. }
  33. var ch = (char)as_read;
  34. if (ch == '\n')
  35. {
  36. buffer.Append(ch);
  37. return ReturnAndEmpty();
  38. }
  39. if (ch == '\r')
  40. {
  41. if (tr.Peek() == '\n')
  42. {
  43. buffer.Append(ch);
  44. buffer.Append('\n');
  45. tr.Read();
  46. return ReturnAndEmpty();
  47. }
  48. }
  49. buffer.Append(ch);
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment