I\'ve known that GetBuffer()
on a MemoryStream in C#/.NET has to be used with care, because, as the docs describe here, there can be unused bytes at the end, so
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.