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

CsharpServer Side ProgrammingProgramming

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
raja
Published on 08-Aug-2020 12:30:46
Advertisements