using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace DocumentService.Client.Extensions;
///
/// Extension methods for Stream operations.
///
public static class StreamExtensions
{
///
/// Converts a stream to a Base64-encoded string.
///
/// Source stream
/// Cancellation token
/// Base64-encoded string
public static async Task ToBase64StringAsync(this Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
byte[] bytes = await stream.ToBytesAsync(cancellationToken);
return Convert.ToBase64String(bytes);
}
///
/// Converts a stream to a byte array.
///
/// Source stream
/// Cancellation token
/// Byte array
public static async Task ToBytesAsync(this Stream stream, CancellationToken cancellationToken = default)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is MemoryStream ms)
{
return ms.ToArray();
}
using var memoryStream = new MemoryStream();
#if NET8_0
await stream.CopyToAsync(memoryStream, cancellationToken);
#else
await stream.CopyToAsync(memoryStream);
#endif
return memoryStream.ToArray();
}
///
/// Resets stream position to beginning if seekable.
///
/// Stream to reset
/// The same stream (for chaining)
public static Stream Reset(this Stream stream)
{
if (stream != null && stream.CanSeek)
stream.Position = 0;
return stream!;
}
}