Closed
Description
Background and Motivation
Sometimes we would like to have a stream CopyTo method which can try to fully copies stream data to a byte array, not only to another stream.
If stream is to end, copy returns with actual copied bytes count;
if byte array is written to its length - 1, return byte array length.
Proposed API
namespace System.IO
{
public abstract class Stream
{
+ public int CopyTo(byte[] destination);
+ public virtual Task<int> CopyToAsync(byte[] destination);
+ public virtual Task<int> CopyToAsync(byte[] destination, CancellationToken cancellationToken);
}
}
Usage Examples
var chunkBuffer = new byte[1024];
var copiedByteCount = await sourceStream.CopyToAsync(chunkBuffer, CancellationToken.None);
// treat chunkBuffer[0 ... copiedByteCount] as one complete chunk and use it later
Risks
As previous Stream.CopyTo (Stream) function, it is also a virtual one in abstract class Stream, so that just implement in abstract Stream and no breaking change for user.