Mehdi Hadeli
Mehdi Hadeli

Reputation: 10184

How do I 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#?

Upvotes: 981

Views: 783373

Answers (6)

Budding bro
Budding bro

Reputation: 33

Stream into Byte[]:                                   

MemoryStream memory = (MemoryStream)stream; 

byte[] imageData = memory.ToArray();

Upvotes: 0

Rod Talingting
Rod Talingting

Reputation: 1080

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
    };
}

Upvotes: 10

Cody Gray
Cody Gray

Reputation: 244951

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);

Upvotes: 437

Corey Ogburn
Corey Ogburn

Reputation: 24759

Look into the MemoryStream class.

Upvotes: 4

QrystaL
QrystaL

Reputation: 4966

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);
    }
}

Upvotes: 36

Martin Buberl
Martin Buberl

Reputation: 47164

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

Stream stream = new MemoryStream(byteArray);

Upvotes: 1657

Related Questions