Files
MSEssentials.Extensions/MSEssentials.Extensions/StreamExtensions.cs
Mateusz Skoczek 4218851796
All checks were successful
Build and publish package / Build (push) Successful in 18s
Build and publish package / Determine version (push) Successful in 20s
Build and publish package / Pack (push) Successful in 19s
Build and publish package / Publish (push) Successful in 14s
rename
2026-04-15 22:47:59 +02:00

37 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MSEssentials.Extensions
{
public static class StreamExtensions
{
public static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress<long> progress = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);
if (!source.CanRead)
{
throw new ArgumentException("Has to be readable", nameof(source));
}
ArgumentNullException.ThrowIfNull(destination);
if (!destination.CanWrite)
{
throw new ArgumentException("Has to be writable", nameof(destination));
}
ArgumentOutOfRangeException.ThrowIfNegative(bufferSize);
var buffer = new byte[bufferSize];
long totalBytesRead = 0;
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead;
progress?.Report(totalBytesRead);
}
}
}
}