System.IO.FileStream.CopyToAsync C# (CSharp) Method

CopyToAsync() public method

public CopyToAsync ( Stream destination, int bufferSize, CancellationToken cancellationToken ) : Task
destination Stream
bufferSize int
cancellationToken CancellationToken
return Task
        public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
        {
            // If we're in sync mode, just use the shared CopyToAsync implementation that does
            // typical read/write looping.  We also need to take this path if this is a derived
            // instance from FileStream, as a derived type could have overridden ReadAsync, in which
            // case our custom CopyToAsync implementation isn't necessarily correct.
            if (!_useAsyncIO || GetType() != typeof(FileStream))
            {
                return base.CopyToAsync(destination, bufferSize, cancellationToken);
            }

            StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);

            // Bail early for cancellation if cancellation has been requested
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<int>(cancellationToken);
            }

            // Fail if the file was closed
            if (_fileHandle.IsClosed)
            {
                throw Error.GetFileNotOpen();
            }

            // Do the async copy, with differing implementations based on whether the FileStream was opened as async or sync
            Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both.");
            return AsyncModeCopyToAsync(destination, bufferSize, cancellationToken);
        }

Usage Example

 public async Task Perform()
 {
     using (var sourceStream = new FileStream(_oldPath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous | FileOptions.DeleteOnClose))
     {
         using (var destinationStream = new FileStream(_newPath, FileMode.Create, FileAccess.Write, FileShare.None, DefaultBufferSize, FileOptions.Asynchronous))
         {
             await sourceStream.CopyToAsync(destinationStream);
         }
     }
 }
All Usage Examples Of System.IO.FileStream::CopyToAsync