StreamExtension, um Zeilenweise zu lesen
This commit is contained in:
68
AMWD.Common/Extensions/StreamExtensions.cs
Normal file
68
AMWD.Common/Extensions/StreamExtensions.cs
Normal file
@@ -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<byte>();
|
||||||
|
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<string> 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<byte>();
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user