86 lines
2.3 KiB
C#
86 lines
2.3 KiB
C#
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace System.IO
|
|
{
|
|
/// <summary>
|
|
/// Provides extension methods for the <see cref="Stream"/>.
|
|
/// </summary>
|
|
public static class StreamExtensions
|
|
{
|
|
/// <summary>
|
|
/// Reads a line from a <see cref="Stream"/>.
|
|
/// </summary>
|
|
/// <param name="stream">The stream to read from.</param>
|
|
/// <param name="encoding">The encoding to use.</param>
|
|
/// <param name="eol">The character determinating a line end.</param>
|
|
/// <returns></returns>
|
|
public static string ReadLine(this Stream stream, Encoding encoding = null, char? eol = null)
|
|
{
|
|
if (encoding == null)
|
|
encoding = Encoding.Default;
|
|
|
|
if (eol == null)
|
|
eol = Environment.NewLine.Last();
|
|
|
|
if (!stream.CanRead)
|
|
return null;
|
|
|
|
var bytes = new List<byte>();
|
|
char ch;
|
|
do
|
|
{
|
|
int result = stream.ReadByte();
|
|
if (result == -1)
|
|
break;
|
|
|
|
byte b = (byte)result;
|
|
bytes.Add(b);
|
|
ch = (char)result;
|
|
}
|
|
while (ch != eol);
|
|
|
|
return encoding.GetString(bytes.ToArray()).Trim();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads a line from a <see cref="Stream"/> asynchronous.
|
|
/// </summary>
|
|
/// <param name="stream">The stream to read from.</param>
|
|
/// <param name="encoding">The encoding to use.</param>
|
|
/// <param name="eol">The character determinating a line end.</param>
|
|
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
|
|
/// <returns></returns>
|
|
public static async Task<string> ReadLineAsync(this Stream stream, Encoding encoding = null, char? eol = null, CancellationToken cancellationToken = default)
|
|
{
|
|
if (encoding == null)
|
|
encoding = Encoding.Default;
|
|
|
|
if (eol == null)
|
|
eol = Environment.NewLine.Last();
|
|
|
|
if (!stream.CanRead)
|
|
return null;
|
|
|
|
var bytes = new List<byte>();
|
|
char ch;
|
|
do
|
|
{
|
|
byte[] buffer = new byte[1];
|
|
int count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
|
|
if (count == 0)
|
|
break;
|
|
|
|
bytes.Add(buffer[0]);
|
|
ch = (char)buffer[0];
|
|
}
|
|
while (ch != eol);
|
|
|
|
return encoding.GetString(bytes.ToArray()).Trim();
|
|
}
|
|
}
|
|
}
|