How to Convert Struct System.Byte Byte[] to a System.Io.Stream Object in C#

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

Superimpose a stream on top of a byte array

The MemoryStream constructor you mentioned in the second block actually does what you want. It saves the array you provide and uses that as the backing buffer for the stream. You can modify the array and those changes will be reflected by the stream if those bytes are still yet to be read.

Here's a minimal reproducible example to demonstrate this.

byte[] source = new byte[] { 0, 1, 2, 3 };
MemoryStream stream = new MemoryStream(source);

// If the constructor made a copy, the stream won't be
// affected and it will output 0 below.
source[0] = 10;

byte b = (byte)stream.ReadByte();

Console.WriteLine(b);

Output:

10

Try it out!

Be aware that the stream cannot grow when you use that constructor. According to its documentation:

The length of the stream cannot be set to a value greater than the initial length of the specified byte array; however, the stream can be truncated (see SetLength).

Allowing it to grow would break the expectation that it's using that buffer because growing would require allocating a new array and copying the data to it.

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);


Related Topics



Leave a reply



Submit