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
Cannot Use Ref or Out Parameter in Lambda Expressions
How to Store User Settings for a .Net Application
Programmatically Determine a Duration of a Locked Workstation
How to Detect the Character Encoding of a Text File
When Is It Better to Use String.Format VS String Concatenation
How to Download HTML Source in C#
Performance Surprise with "As" and Nullable Types
How to Get Memory Available or Used in C#
How to Start Winform App Minimized to Tray
How to Create Dynamic Properties in C#
How to Run Another Application Within a Panel of My C# Program
Testing If Object Is of Generic Type in C#
"A Namespace Cannot Directly Contain Members Such as Fields or Methods"
Deserializing JSON When Sometimes Array and Sometimes Object