Convert Stream to Byte Array in C#

Muhammad Maisam Abbas Jan 30, 2023 Mar 13, 2021
  1. Convert Stream to byte[] With the Stream.CopyTo() Function in C#
  2. Convert MemoryStream to byte[] With the MemoryStream.ToArray() Function in C#
Convert Stream to Byte Array in C#

This tutorial will introduce methods to convert a stream to a byte array in C#.

Convert Stream to byte[] With the Stream.CopyTo() Function in C#

The Stream.CopyTo(memoryStream) function copies bytes from the Stream to the memoryStream in C#. We can use the Stream.CopyTo() function along with the object of the MemoryStream class to convert a stream to a byte array. The following code example shows us how to convert a stream to a byte array with the Stream.CopyTo() function in C#.

using System;
using System.IO;

namespace stream_to_byte_array
{
    class Program
    {
        public static byte[] streamToByteArray(Stream input)
        {
            MemoryStream ms = new MemoryStream();
            input.CopyTo(ms);
            return ms.ToArray();
        }
        static void Main(string[] args)
        {
        }
    }
}

In the above code, the streamToByteArray() takes a Stream object as a parameter, converts that object into a byte[], and returns the result. We create the MemoryStream object ms to store a copy of the contents of the input stream. We copy the contents of the input stream to the ms memory stream with the input.CopyTo(ms) function in C#. We return the copied content in the form of an array with the ms.ToArray() function.

Convert MemoryStream to byte[] With the MemoryStream.ToArray() Function in C#

In the above method, we create a Memorystream to convert a Stream to a byte[]. If we have a MemoryStream instead of a Stream, we can use the MemoryStream.ToArray() function. The MemoryStream.ToArray() function converts the content of the MemoryStream to a byte array in C#. The return type of the MemoryStream.ToArray() function is byte[]. The following code example shows us how we can convert a MemoryStream to a byte[] with the MemoryStream.ToArray() function in C#.

MemoryStream ms = new MemoryStream();
byte[] byteArray = ms.ToArray();

We converted the MemoryStream object ms to the byteArray with the ms.ToArray() function in C#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp Stream

Related Article - Csharp Byte Array