Home >Backend Development >C++ >How to Efficiently Convert a C# Stream to a byte[]?

How to Efficiently Convert a C# Stream to a byte[]?

DDD
DDDOriginal
2025-01-12 11:05:46335browse

How to Efficiently Convert a C# Stream to a byte[]?

Transforming C# Streams into byte[] Arrays: A Practical Guide

Frequently, C# developers encounter scenarios requiring the conversion of a Stream (a linear data flow) into a byte array. This is especially relevant when dealing with binary data or network communication.

Efficient Stream-to-byte[] Conversion Technique

The most effective approach involves these steps:

  1. Instantiate a MemoryStream object to store the converted data.
  2. Utilize the CopyTo method to transfer data from the source Stream to the MemoryStream.
  3. Employ the ToArray method to extract the byte array from the populated MemoryStream.

Below is a concise code example illustrating this process:

<code class="language-csharp">using (var memoryStream = new MemoryStream())
{
    sourceStream.CopyTo(memoryStream);
    byte[] byteArray = memoryStream.ToArray();
    return byteArray;
}</code>

The above is the detailed content of How to Efficiently Convert a C# Stream to a byte[]?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn