Home >Backend Development >C++ >How to Efficiently Convert a C# Stream to a Byte Array?
C# stream to byte array conversion
Question: How to efficiently convert a Stream object in C# to a byte array?
Answer:
Using the CopyTo method, you can accomplish this conversion directly. Please refer to the following code snippet:
<code class="language-csharp">using (var memoryStream = new MemoryStream()) { sourceStream.CopyTo(memoryStream); return memoryStream.ToArray(); }</code>
This code creates a MemoryStream object and uses the CopyTo method to copy the contents of the sourceStream to the memoryStream. Finally, it returns the contents of memoryStream as a byte array.
The above is the detailed content of How to Efficiently Convert a C# Stream to a Byte Array?. For more information, please follow other related articles on the PHP Chinese website!