简体   繁体   English

无法使用BinaryWriter写入MemoryStream

[英]Cannot write to MemoryStream using BinaryWriter

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. 每次运行时,都会抛出NotSupportedException,告诉我无法写入流。 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. 第2行中显示的初始化的最后一个参数显然是正确的,所以我应该能够写入流。 It works if I don't specify the start index and count. 如果我没有指定起始索引和计数,它可以工作。

Why does this happen? 为什么会这样?

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 这段代码工作正常

From MSDN : 来自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. 基于字节数组的指定区域初始化MemoryStream类的新的不可调整大小的实例,并将CanWrite属性设置为指定的。

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. BinaryWriter开始在流的末尾写入,因此需要调整它以便能够写入,但这是不允许的。 You can only write to the already allocated bytes of the stream. 您只能写入已分配的流的字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM