When is GetBuffer() on MemoryStream ever useful?
If you really want to access the internal _origin Value, you may use the MemoryStream.Seek(0, SeekOrigin.Begin) call. The return Value will be exactly the _origin Value.
.NET 4.6 has a new API, bool MemoryStream.TryGetBuffer(out ArraySegment<byte> buffer)
that is similar in spirit to .GetBuffer()
. This method will return an ArraySegment
that includes the _origin
information if it can.
See this question for details about when .TryGetBuffer()
will return true and populate the out param with useful information.
The answer is in the GetBuffer() MSDN doc, you might have missed it.
When you create a MemoryStream
without providing a byte array (byte[]
) :
it creates an expandable capacity initialized to zero.
In other words, the MemoryStream will reference to a byte[]
with the proper size when a Write
call will be made on the Stream.
Thus, with GetBuffer()
you can directly access the underlying array and read to it.
This could be useful when you're in the situation that you will receive a stream without knowing its size. If the stream received is usually very big, it will be much faster to call GetBuffer()
than calling ToArray()
which copy the data under the hood, see below.
To obtain only the data in the buffer, use the ToArray method; however, ToArray creates a copy of the data in memory.
I wonder at which point you might have called GetBuffer() to get junk data at the beginning, it could be between two Write
calls where the data from the first one would have been garbage collected, but I'm not sure if that could happen.