snippetcsharpCritical
How do I copy the contents of one stream to another?
Viewed 0 times
streamhowcontentsthecopyoneanother
Problem
What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?
Solution
From .NET 4.5 on, there is the
This will return a
Note that depending on where the call to
The
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
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:
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
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
Stream.CopyToAsync methodinput.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 methodinput.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.
Code Snippets
input.CopyToAsync(output);await input.CopyToAsync(output)
// Code from here on will be run in a continuation.input.CopyTo(output);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);
}
}Context
Stack Overflow Q#230128, score: 748
Revisions (0)
No revisions yet.