Why does MemoryStream.GetBuffer() always throw?

后端 未结 4 1579
滥情空心
滥情空心 2021-01-03 22:21

The following code will always throw UnuthorizedAccessException (MemoryStream\'s internal buffer cannot be accessed.)

byte[] buf1 = { 2, 3, 5, 7, 11 };
var         


        
相关标签:
4条回答
  • 2021-01-03 22:32

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

    0 讨论(0)
  • 2021-01-03 22:37

    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();
    
    0 讨论(0)
  • 2021-01-03 22:40

    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.

    0 讨论(0)
  • 2021-01-03 22:42

    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.

    0 讨论(0)
提交回复
热议问题