Thursday, June 04, 2009

.NET Funda : MemoryStream ToArray() vs. GetBuffer()

Look at the following program.

 class Program
{
static void Main(string[] args)
{
MemoryStream ms = new MemoryStream();
//write 10 bytes to the memory stream.
for (byte i = 65; i < 75; i++)
ms.WriteByte(i);

System.Console.WriteLine("MemoryStream.GetBuffer() : {0}",
ms.GetBuffer().Length);
System.Console.WriteLine("MemoryStream.ToArray() : {0}",
ms.ToArray().Length);

System.Console.WriteLine("GetBuffer() BytesToString : {0}",
FromBytesToString(ms.GetBuffer()));
System.Console.WriteLine("ToArray() BytesToString : {0}",
FromBytesToString(ms.ToArray()));

ms.Close();
System.Console.WriteLine("GetBuffer() BytesToString : {0}",
FromBytesToString(ms.GetBuffer()));
System.Console.WriteLine("ToArray() BytesToString {0}",
FromBytesToString(ms.ToArray()));
}

public static string FromBytesToString(byte[] b)
{
return ASCIIEncoding.Default.GetString(b);
}
}


In the above code, we use a MemoryStream and write 10 bytes (from A(65) to J(74)).  Running the program gives the following result.



image



The first two print statements displays the length of the byte[] array returned by both GetBuffer() and ToArray(). Now, both these methods returns the byte[] written to the memory stream but the difference is that GetBuffer() returns the allocated byte buffer used by the memory stream and this also includes the unused bytes where as ToArray() returns only the used bytes from the buffer.



Since a memory stream is initialized with a byte array of size 256, even though only 10 bytes have been written to the stream, the buffer returned is of size 256 (of which only 10 bytes are used). Printing the Bytes to string, thus displays a long series of empty lines where as ToArray() returns only 10 bytes that were used and displays the string exactly of size 10.



Note that both these methods work even when the stream is closed (demonstrated by the last two print lines in the code above).



The usage becomes important especially when you are trying to perform in-memory deserialization of some object from the memory stream for reasons like the binary data would be totally different from what was written actually, when using  GetBuffer().

1 comment:

Rennie said...

Thank you.