using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AMWD.Common.Extensions { public static class StreamExtensions { public static string ReadLine(this Stream stream, Encoding encoding = null, string eol = null) { if (encoding == null) encoding = Encoding.Default; if (eol == null) eol = Environment.NewLine; if (!stream.CanRead) return null; var bytes = new List(); string s; do { int result = stream.ReadByte(); if (result == -1) break; byte b = (byte)result; bytes.Add(b); s = encoding.GetString(new[] { b }); } while (!eol.Contains(s)); return encoding.GetString(bytes.ToArray()).Trim(); } public static async Task ReadLineAsync(this Stream stream, Encoding encoding = null, string eol = null, CancellationToken cancellationToken = default) { if (encoding == null) encoding = Encoding.Default; if (eol == null) eol = Environment.NewLine; if (!stream.CanRead) return null; var bytes = new List(); string s; do { byte[] buffer = new byte[1]; int count = await stream.ReadAsync(buffer, 0, buffer.Length); if (count == 0) break; bytes.Add(buffer[0]); s = encoding.GetString(buffer); } while (!eol.Contains(s)); return encoding.GetString(bytes.ToArray()).Trim(); } } }