C# › File I/O & Streams

How do you correctly implement async, cancellable file I/O using CancellationToken with FileStream operations?

Advanced

Answer

Pass a CancellationToken through to the async overloads of ReadAsync/WriteAsync/CopyToAsync — these methods periodically check for cancellation and throw an OperationCanceledException promptly if the token is signaled mid-operation, letting long-running file I/O be cleanly cancelled rather than blocking until completion regardless of a cancellation request.
async Task CopyLargeFileAsync(string source, string dest, CancellationToken token) {
  using FileStream sourceStream = File.OpenRead(source);
  using FileStream destStream = File.Create(dest);
  await sourceStream.CopyToAsync(destStream, token); // respects cancellation mid-copy
}
Real-world example Allowing a user to cancel a large file upload or copy operation mid-way through, rather than forcing them to wait for it to finish.

Common follow-ups: What happens to a partially-written destination file if the copy operation is cancelled midway?