为什么MemoryStream.GetBuffer()总是抛出? [英] Why does MemoryStream.GetBuffer() always throw?
问题描述
以下代码将始终抛出
UnuthorizedAccessException(MemoryStream的内部缓冲区无法访问。)
The following code will always throw UnuthorizedAccessException (MemoryStream's internal buffer cannot be accessed.)
byte[] buf1 = { 2, 3, 5, 7, 11 };
var ms = new MemoryStream(buf1);
byte[] buf2 = ms.GetBuffer(); // exception will be thrown here
这是一个简单的旧控制台应用程序,我正在运行管理员。我无法想象一个更特权的设置,我可以给这个代码。那为什么我不能得到这个缓冲区? (如果没有人可以,GetBuffer方法的重点是什么?)
This is in a plain old console app and I'm running as an admin. I can't imagine a more privileged setting I could give this code. So why can't I get at this buffer? (And if nobody can, what's the point of the GetBuffer method?)
MSDN文档说
要创建一个具有
a公开可见缓冲区的MemoryStream实例,请使用
MemoryStream,
MemoryStream(array [],Int32,
Int32,Boolean,Boolean)或
MemoryStream(Int32)。
To create a MemoryStream instance with a publicly visible buffer, use MemoryStream, MemoryStream(array[], Int32, Int32, Boolean, Boolean), or MemoryStream(Int32).
我不是这样吗?
PS我不想使用ToArray(),因为这是一个副本。
P.S. I don't want to use ToArray() because that makes a copy.
推荐答案
这里是 MemoryStream(byte [])的文档
你正在使用的构造函数它具体说:
Here is the documentation for MemoryStream(byte[])
constructor that you're using. It specifically says:
此构造函数不会公开底层流。 GetBuffer throws UnauthorizedAccessException。
This constructor does not expose the underlying stream. GetBuffer throws UnauthorizedAccessException.
You should use this constructor instead, with publiclyVisible = true
.
这篇关于为什么MemoryStream.GetBuffer()总是抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!