3

I've tried this code:

byte[] someData = new byte[] { 1, 2, 3, 4 };
MemoryStream stream = new MemoryStream(someData, 1, someData.Length - 1, true);
using (BinaryWriter writer = new BinaryWriter(stream))
{
    writer.Write(1);
}
stream.Dispose();

Everytime it's run, a NotSupportedException is thrown, telling me that the stream cannot be written to. Why is this the case? The last parameter of the initialization shown in line 2 clearly is true, so I should be able to write to the stream. It works if I don't specify the start index and count.

Why does this happen?

2 Answers 2

14

Always (almost always) create a memory stream without parameters in the constructor:

 using (MemoryStream stream = new MemoryStream())
        {
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                writer.Write(1);
            }
            stream.Flush();
            byte[] bytes = stream.GetBuffer();
            //use it
        }

This code works fine

2
  • Thanks. That indeed works. I'll have to copy the contents of someData manually since I don't want the first index to be in the Stream, but that's not that bad.
    – haiyyu
    Jan 29, 2012 at 23:43
  • @haiyyu - note that an alternative to copying the data is to make an enumerator that returns the desired data as a stream. Jan 26, 2018 at 17:28
4

From MSDN:

Initializes a new non-resizable instance of the MemoryStream class based on the specified region of a byte array, with the CanWrite property set as specified.

The BinaryWriter starts writing at the end of the stream, so it needs to resize it to be able to write, but this is not allowed. You can only write to the already allocated bytes of the stream.

1
  • See Mudx's answer for what to do instead. Specifically, OP needs to use a different constructor; then they can get the desired behavior. [In their case, it means they need to first either (a) copy the data they wish to stream, or (b) make an enumerator that streams the desired data.] Jan 26, 2018 at 17:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.