From 37650db1e15a83a1a63def5f1052e9612ffe8009 Mon Sep 17 00:00:00 2001 From: Andreas Mueller Date: Fri, 17 Dec 2021 22:27:52 +0100 Subject: [PATCH] StreamExtension, um Zeilenweise zu lesen --- AMWD.Common/Extensions/StreamExtensions.cs | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 AMWD.Common/Extensions/StreamExtensions.cs diff --git a/AMWD.Common/Extensions/StreamExtensions.cs b/AMWD.Common/Extensions/StreamExtensions.cs new file mode 100644 index 0000000..a83d825 --- /dev/null +++ b/AMWD.Common/Extensions/StreamExtensions.cs @@ -0,0 +1,68 @@ +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(); + } + } +}