Home >Backend Development >C++ >How to Efficiently Convert a C# Stream to a Byte Array?

How to Efficiently Convert a C# Stream to a Byte Array?

DDD
DDDOriginal
2025-01-12 10:49:41304browse

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!

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