Reusing Memory Streams

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0.

MemoryStream ms = new MemoryStream();

// Do some stuff with the stream

// Reset the stream so you can re-use it
ms.Position = 0; // Not actually needed, SetLength(0) will reset the Position anyway
ms.SetLength(0);

// Do some more stuff with the stream

By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters. So the existing buffer allocation remains intact, but all the book keeping of how much of the buffer is used is reset so that you can re-use it.

Update: I just took a quick look at the code implementation for SetLength and if you set the length to 0 the Position will automatically be reset to 0 so you do not even need to explicitly set the Position property it is enough to just reset the length.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)