Why does MemoryStream.GetBuffer() always throw?

北战南征 提交于 2019-12-01 03:00:06

Here is the documentation for MemoryStream(byte[]) constructor that you're using. It specifically says:

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

You should use this constructor instead, with publiclyVisible = true.

Check the docs for 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.

You need to use a different constructor.

To add to what others have already put in here...

Another way to get your code to work is change your code to the following line.

byte[] buf2 = ms.ToArray();

You appear to be using MemoryStream(array[]) which does not match any of the three versions mentioned in the docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!