Search code examples
.netmemorystream

Reset or Clear .NET MemoryStream


The .NET MemoryStream does not appear to have a .Reset or .Clear method.

I was thinking of using the following code to accomplish this:

ms.Seek(0, IO.SeekOrigin.Begin)
ms.SetLength(0)

What is the proper way to clear or reset an existing .NET MemoryStream?


Solution

  • The memorystream does not have a reset/clear method because it would be redundant. By setting it to zero length you clear it.

    Of course you could always do:

    memoryStream = new MemoryStream(memoryStream.Capacity());
    

    This would yield you a memorystream of the same size that is initialized.

    If you really want to manually clear the stream I suspect you would have to resort to looping through the elements.