Miguel Moura
Miguel Moura

Reputation: 39514

Convert Stream to Byte Array

I created a simple extension to convert a Stream to Byte array:

public static Byte[] ToByte(this Stream value) 
{
  if (value == null)
    return null;

  if (value is MemoryStream)
  {
    return ((MemoryStream)value).ToArray();
  }
  else 
  {
     using (MemoryStream stream = new MemoryStream()) 
     {
          value.CopyTo(stream);
          return stream.ToArray();
      }
  }

}

This works fine the first time I use it ...

If I use it a second time on the same stream the resulting Byte[] is Byte[0].

I debugged and I think this happens because after the first conversion the Stream index goes to the end of the stream.

What is the correct way to fix this?

Upvotes: 1

Views: 1453

Answers (2)

mreiterer
mreiterer

Reputation: 556

set the stream index to the beginning.

stream.Seek(0, SeekOrigin.Begin);

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61379

As you say, you are at the end of the stream after the first read. Thus, you need to reset the memory stream with:

stream.Seek(0, SeekOrigin.Begin);

Or

stream.Position = 0;

Before reading it again. Note that CanSeek on the stream must be true for either approach to work. MemoryStream is fine, some other streams will have this set to false.

Upvotes: 8

Related Questions