How to Convert a Stream to Byte Array in C# 4.0 ?

One of the simplest way to convert a stream to byte array in C# 4.0 is to use the MemoryStream and perform the CopyTo operation on the source stream to the Memory Stream.

How to Convert a Stream to Byte Array in C# 4.0 ?

Below is a sample code snippet on how to convert a stream to byte array in C# 4.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace AbundantCode
{
    internal class Program
    {     
        private static void Main(string[] args)
        {
            Stream InputStream = null; // Get the input value from the file/other source
            byte[] result;
            using (var streamReader = new MemoryStream())
            {
                InputStream.CopyTo(streamReader);
                result = streamReader.ToArray();
            }
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}
Tags :

2 Comments

  • We can just use MemoryStream ms = new MemoryStream(bytes); Where bytes is byte array.

  • Thank you. It’s what I was looking for!

Leave Your Comment