Copy Stream To Async - CSharp File IO

CSharp examples for File IO:File Command

Description

Copy Stream To Async

Demo Code


using System.Threading.Tasks;
using System.IO;//from w  w w  .  j  a va  2s . c  o  m
using System;

public class Main{
        public static async Task CopyToAsync(this Stream source, Stream destination, IProgress<CopyToAsyncProgress> progress)
        {
            var buffer = new byte[81920];
            var totalBytesToRead = source.CanSeek ? source.Length : -1;
            long totalBytesRead = 0;
            int bytesRead;

            while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0)
            {
                await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                totalBytesRead += bytesRead;
                progress.Report(new CopyToAsyncProgress(totalBytesRead, totalBytesToRead));
            }
        }
}

Related Tutorials