关于windows:为什么MemoryStream.GetBuffer()总是抛出?

Why does MemoryStream.GetBuffer() always throw?

总是会把下面代码unuthorizedaccessexception(memorystream'内部缓冲accessed cannot be)。P></

1
2
3
byte[] buf1 = { 2, 3, 5, 7, 11 };
var ms = new MemoryStream(buf1);
byte[] buf2 = ms.GetBuffer();      // exception will be thrown here

This is a平原在控制台应用程序运行在管理员* m as an。我不能想象在我的黑莓privileged设置给这个队列。我为什么不能让at this缓冲?(如果没有人做点什么,the method of the getbuffer?)P></

在MSDN文档。P></

To create a MemoryStream instance with
a publicly visible buffer, use
MemoryStream,
MemoryStream(array[], Int32,
Int32, Boolean, Boolean), or
MemoryStream(Int32).

我不做那?P></

我不想让你因为使用toarray(复制)。P></


这是您正在使用的MemoryStream(byte[])构造函数的文档。它特别指出:

This constructor does not expose the underlying stream. GetBuffer throws UnauthorizedAccessException.

号

您应该使用这个构造函数来代替publiclyVisible = true。


检查文档中是否有memoryStream.getBuffer()。

To create a MemoryStream instance with
a publicly visible buffer, use
MemoryStream, MemoryStream(Byte[],
Int32, Int32, Boolean, Boolean), or
MemoryStream(Int32). If the current
stream is resizable, two calls to this
method do not return the same array if
the underlying byte array is resized
between calls. For additional
information, see Capacity.

号

您需要使用不同的构造函数。


加上其他人已经放在这里的东西…

另一种让代码工作的方法是将代码更改为以下行。

1
byte[] buf2 = ms.ToArray();

您似乎使用的MemoryStream(array[])与文档中提到的三个版本中的任何一个都不匹配。