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

How to Efficiently Convert an Input Stream to a Byte Array in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-31 06:56:09309browse

How to Efficiently Convert an Input Stream to a Byte Array in C#?

C# Input Stream to Byte Array: A Practical Guide

Converting an input stream into a byte array is a common task when handling binary data in C#. The best method depends on whether you know the stream's size.

Known Stream Size:

If the stream's length is available, BinaryReader.ReadBytes offers a simple solution:

<code class="language-csharp">using (BinaryReader br = new BinaryReader(s))
{
    byte[] b = br.ReadBytes((int)s.Length);
}</code>

This directly reads the entire stream into a byte array.

Unknown Stream Size:

For streams with unknown lengths, a more robust, iterative approach is necessary:

<code class="language-csharp">using (MemoryStream ms = new MemoryStream())
{
    byte[] buffer = new byte[16 * 1024]; // Adjust buffer size as needed
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        ms.Write(buffer, 0, read);
    }
    byte[] b = ms.ToArray();
}</code>

This method reads the stream in chunks, accumulating the data in a MemoryStream before converting it to a byte array.

.NET 4 and Above: Stream.CopyTo

.NET 4 and later versions offer a more efficient and concise solution using Stream.CopyTo:

<code class="language-csharp">using (MemoryStream ms = new MemoryStream())
{
    input.CopyTo(ms);
    byte[] b = ms.ToArray();
}</code>

This elegantly handles streams of any size.

Performance and Resource Management:

Remember that reading in chunks can impact performance. Experiment with different buffer sizes to optimize for your specific needs. Always ensure proper stream closure to avoid resource leaks.

The above is the detailed content of How to Efficiently Convert an Input Stream to a Byte Array in C#?. 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