How do I copy the contents of one stream to another?


What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?

9/26/2014 5:12:02 PM

Accepted Answer

From .NET 4.5 on, there is the Stream.CopyToAsync method


This will return a Task that can be continued on when completed, like so:

await input.CopyToAsync(output)

// Code from here on will be run in a continuation.

Note that depending on where the call to CopyToAsync is made, the code that follows may or may not continue on the same thread that called it.

The SynchronizationContext that was captured when calling await will determine what thread the continuation will be executed on.

Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).

From .NET 4.0 on, there's is the Stream.CopyTo method


For .NET 3.5 and before

There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:

public static void CopyStream(Stream input, Stream output)
    byte[] buffer = new byte[32768];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        output.Write (buffer, 0, read);

Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length? Because that Length may not be available! From the docs:

If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.

9/24/2018 12:14:53 PM

MemoryStream has .WriteTo(outstream);

and .NET 4.0 has .CopyTo on normal stream object.

.NET 4.0:


I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.

    public static void CopyTo(this Stream src, Stream dest)
        int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
        byte[] buffer = new byte[size];
        int n;
            n = src.Read(buffer, 0, buffer.Length);
            dest.Write(buffer, 0, n);
        } while (n != 0);           

    public static void CopyTo(this MemoryStream src, Stream dest)
        dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));

    public static void CopyTo(this Stream src, MemoryStream dest)
        if (src.CanSeek)
            int pos = (int)dest.Position;
            int length = (int)(src.Length - src.Position) + pos;

            while(pos < length)                
                pos += src.Read(dest.GetBuffer(), pos, length - pos);

The basic questions that differentiate implementations of "CopyStream" are:

  • size of the reading buffer
  • size of the writes
  • Can we use more than one thread (writing while we are reading).

The answers to these questions result in vastly different implementations of CopyStream and are dependent on what kind of streams you have and what you are trying to optimize. The "best" implementation would even need to know what specific hardware the streams were reading and writing to.


There is actually, a less heavy-handed way of doing a stream copy. Take note however, that this implies that you can store the entire file in memory. Don't try and use this if you are working with files that go into the hundreds of megabytes or more, without caution.

public static void CopySmallTextStream(Stream input, Stream output)
  using (StreamReader reader = new StreamReader(input))
  using (StreamWriter writer = new StreamWriter(output))

NOTE: There may also be some issues concerning binary data and character encodings.


.NET Framework 4 introduce new "CopyTo" method of Stream Class of System.IO namespace. Using this method we can copy one stream to another stream of different stream class.

Here is example for this.

    FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
    Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));

    MemoryStream objMemoryStream = new MemoryStream();

    // Copy File Stream to Memory Stream using CopyTo method
    Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]