Back to results for “Asynchronous Programming”
C# › File I/O & Streams

How do you efficiently copy data between two streams using Stream.CopyToAsync(), and why is this preferred over a manual byte-by-byte loop?

Intermediate

Answer

CopyToAsync() efficiently transfers data from a source stream to a destination stream using an internally-managed BUFFER (reading a chunk, writing it, repeating), fully asynchronously — far more efficient and less error-prone than manually implementing your own read/write loop with a byte array.
using FileStream source = File.OpenRead("large-file.dat");
using FileStream destination = File.Create("copy.dat");
await source.CopyToAsync(destination); // efficient, buffered, fully async
Real-world example Copying a large uploaded file from a temporary location to permanent storage without loading the entire file into memory.

Common follow-ups: Can CopyToAsync() also be used between fundamentally different stream types, like a network stream and a file stream?