Skip to content

virtual Task CopyToAsync(byte[] destination, CancellationToken cancellationToken) (and its sync version) for abstract class Stream #42109

Closed
@handlespeed

Description

@handlespeed

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.IO

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions