What is the best way to copy the contents of one stream to another? Is there a standard utility method for this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From .NET 4.5 on, there is the
Stream.CopyToAsyncmethodThis will return a
Taskthat can be continued on when completed, like so:Note that depending on where the call to
CopyToAsyncis made, the code that follows may or may not continue on the same thread that called it.The
SynchronizationContextthat was captured when callingawaitwill 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.CopyTomethodFor .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
input.Length? Because that Length may not be available! From the docs: