Thursday, October 15, 2009

Reading data from a closed Stream

Problem:
Sometimes you need to read data from a Stream, either to save it or to process it in other layers, but you really don't want to open or pass along the Stream for too long.

Solution:
At first glance, the GetBuffer() method of the Stream object would seem ideal, since it copies the text to a byte array, allowing you to close the underlying stream without any issues.

However, GetBuffer has some definite issues, the biggest one being that he will pad the resulting byte array with "\0" (nulls), depending on how big the data in your stream is. Which can lead to all kinds of nasty side-effects (in particular when working with XML data).

Never fear, in comes the rescuer, in this case the ToArray() method of the Stream object. This basically does everything GetBuffer does, minus the padding. And likewise, you can simply dispose of the Stream and do whatever you need to do with the data.

No comments: