Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

stream

copying

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

like image 820
Anton Avatar asked Oct 23 '08 15:10

Anton


People also ask

How do I write from one stream to another?

Stream.CopyToAsync Method (System.IO)Asynchronously reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

What is the difference between stream and MemoryStream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.


2 Answers

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

input.CopyToAsync(output); 

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

input.CopyTo(output); 

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.

like image 118
9 revs, 8 users 28% Avatar answered Oct 19 '22 23:10

9 revs, 8 users 28%


MemoryStream has .WriteTo(outstream);

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

.NET 4.0:

instream.CopyTo(outstream); 
like image 23
Joshua Avatar answered Oct 19 '22 22:10

Joshua