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

C#.NetArraysStream

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Stream stream = new MemoryStream(byteArray);

Solution 2 - C#

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

Solution 3 - C#

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

Solution 4 - C#

Look into the MemoryStream class.

Solution 5 - C#

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehdi HadeliView Question on Stackoverflow
Solution 1 - C#Martin BuberlView Answer on Stackoverflow
Solution 2 - C#Cody GrayView Answer on Stackoverflow
Solution 3 - C#QrystaLView Answer on Stackoverflow
Solution 4 - C#Corey OgburnView Answer on Stackoverflow
Solution 5 - C#Rod TalingtingView Answer on Stackoverflow