65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
using System.IO;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace DocumentService.Client.Extensions;
|
|
|
|
/// <summary>
|
|
/// Extension methods for Stream operations.
|
|
/// </summary>
|
|
public static class StreamExtensions
|
|
{
|
|
/// <summary>
|
|
/// Converts a stream to a Base64-encoded string.
|
|
/// </summary>
|
|
/// <param name="stream">Source stream</param>
|
|
/// <param name="cancellationToken">Cancellation token</param>
|
|
/// <returns>Base64-encoded string</returns>
|
|
public static async Task<string> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts a stream to a byte array.
|
|
/// </summary>
|
|
/// <param name="stream">Source stream</param>
|
|
/// <param name="cancellationToken">Cancellation token</param>
|
|
/// <returns>Byte array</returns>
|
|
public static async Task<byte[]> 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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Resets stream position to beginning if seekable.
|
|
/// </summary>
|
|
/// <param name="stream">Stream to reset</param>
|
|
/// <returns>The same stream (for chaining)</returns>
|
|
public static Stream Reset(this Stream stream)
|
|
{
|
|
if (stream != null && stream.CanSeek)
|
|
stream.Position = 0;
|
|
|
|
return stream!;
|
|
}
|
|
}
|