How to convert byte array to an object stream in C#?


Stream is the abstract base class of all streams and it Provides a generic view of a sequence of bytes. The Streams Object involve three fundamental operations such as Reading, Writing and Seeking. A stream be can be reset which leads to performance improvements.

A byte array can be converted to a memory stream using MemoryStream Class.

MemoryStream stream = new MemoryStream(byteArray);

Example

Let us consider a byte array with 5 values 1, 2, 3, 4, 5.

 Live Demo

using System;
using System.IO;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         byte[] byteArray = new byte[5] {1, 2, 3, 4, 5 };
         using (MemoryStream stream = new MemoryStream(byteArray)) {
            using (BinaryReader reader = new BinaryReader(stream)) {
               for (int i = 0; i < byteArray.Length; i++) {
                  byte result = reader.ReadByte();
                  Console.WriteLine(result);
               }
            }
         }
         Console.ReadLine();
      }
   }
}

Output

The output of the above code is

1
2
3
4
5

Updated on: 08-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements