In programming, copying the content of a stream to another is a common operation. .NET provides several methods to implement this operation.
Use Stream.copytoasync method (.NET 4.5)
.NET 4.5 Stream.copytoasync method introduced a method of asynchronous replication flow content:
This method returns a task, which can wait for it to complete to ensure that the operation is completed. It maintains the context and allows the follow -up code to continue to execute on the same thread.
<code class="language-csharp">input.CopyToAsync(output);</code>
In the .NET 4.0 and higher versions, the Stream.copyto method provided a synchronous copy of the flow:
Customized implementation of the customization of .NET 3.5 and earlier versions
<code class="language-csharp">input.CopyTo(output);</code>
Precautions
<code class="language-csharp">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); } }</code>
Please note that the length of the flow may not be available for some stream realization.
The above is the detailed content of How to Efficiently Copy Stream Contents in .NET?. For more information, please follow other related articles on the PHP Chinese website!