1

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?

1
  • Keep in mind, stream is like a pointer to the memory. When you actually finish converting to the array, the pointer is at the end. Make sure to reset it if you do want to run it again. Commented Oct 8, 2014 at 22:38

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This works as long as the stream is seekable (which it should be if it is a MemoryStream). If you are using a different type of stream that is not seekable, you will be out of luck unfortunately.
I also found the option stream.Position = 0; It seems to also work. Is it equivalent to your suggestion?
@MDMoura Yes, it is equivalent, and also requires the stream to be seekable.
1

set the stream index to the beginning.

stream.Seek(0, SeekOrigin.Begin);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.