Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MemoryStream.GetBuffer() always throw?

Tags:

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

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?)

The MSDN docs say

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

Am I not doing that?

P.S. I don't want to use ToArray() because that makes a copy.

like image 334
I. J. Kennedy Avatar asked Oct 29 '09 19:10

I. J. Kennedy


3 Answers

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.

like image 135
Pavel Minaev Avatar answered Oct 05 '22 03:10

Pavel Minaev


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.

like image 25
Dolphin Avatar answered Oct 05 '22 01:10

Dolphin


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();
like image 41
Bomlin Avatar answered Oct 05 '22 01:10

Bomlin