Follow @RoyOsherove on Twitter

[Tip]:MemoryStream.GetBuffer() vs. MemoryStream.ToArray()

One of my readers posted a comment on my Site-To-RSS article that just solved me a bunch of trouble!

In the article, I was using a memory stream to write the XML into memory. I was using the MemoryStream.GetBuffer() method to retrieve the text inside the stream. This caused some ugly code because to get the buffer correctly, I had to know the length of the actual string in the stream, meaning the stream had to be open for me to know that. Even so, it didn't work very well and sometimes retrieved corrupted data.

So, TheCShark (huh?) solved all my problems in one fell swoop by posting one simple line:

Tip: use ToArray instead of GetBuffer, ToArray works when the MemoryStream is closed.

Amazing. All my problems are now solved:

  • No longer need to keep stream open
  • Calling code is much simpler:
    • Dim retval As String = Encoding.UTF8.GetString(ms.ToArray())

  • It works without a hitch!

So, we learned that we should always use ToArray() to get the value. Always. Phew. How silly of me not to notice that!

Thanks, CShark!

A big bug in Google

Excellent TDD articles, and a Code Kata