Home >Backend Development >C++ >How Can I Convert a C# Stream to a Byte Array?
Efficiently Converting C# Streams to Byte Arrays
C# programmers frequently need to transform a Stream
object (representing a byte sequence) into a byte[]
array. This is essential for tasks like file handling, data transmission, and stream processing.
A Streamlined Approach
A clean and efficient solution is as follows:
<code class="language-csharp">using (var memoryStream = new MemoryStream()) { sourceStream.CopyTo(memoryStream); return memoryStream.ToArray(); }</code>
This code uses CopyTo
to efficiently transfer data from sourceStream
to a MemoryStream
. The ToArray()
method then easily extracts the resulting byte array. This approach is both compact and highly effective.
The above is the detailed content of How Can I Convert a C# Stream to a Byte Array?. For more information, please follow other related articles on the PHP Chinese website!