Reset or Clear .NET MemoryStream

.NetMemorystream

.Net Problem Overview


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?

.Net Solutions


Solution 1 - .Net

Why do you need resetting memory stream? You always can create a new one. Or you can use:

memoryStream.SetLength(0);

Solution 2 - .Net

Since a MemoryStream is essentially a byte array with an index (and some other supporting members) clearing the byte array and resetting the index can be considered resetting and clearing the MemoryStream. If the initial state of a MemoryStream is a zeroed array with a position of zero then an example of a MemoryStream reset may be:

public static void Clear(this MemoryStream source)
{
  byte[] buffer = source.GetBuffer();
  Array.Clear(buffer, 0, buffer.Length);
  source.Position = 0;
  source.SetLength(0);
}

It is incorrect to say that MemoryStream.SetLength alone resets or clears the MemoryStream since SetLength only clears the internal buffer array if the length exceeds the current buffer's length.

Reinitializing a MemoryStream is a valid approach but less efficient. One benefit of reinitializing the MemoryStream would be to guarantee that the stream was never closed. Once the MemoryStream is closed it can no longer be changed. If you can ensure that the MemoryStream instance isn't closed then clearing the buffer may be the way to go.

Solution 3 - .Net

I used DotMemory to Profile @Rana_Ian solution, and I called GC to enforce full collection. I found that large Streams will stuck in LOH! And after adding one extra line

public static void Clear(MemoryStream ms)
{
    var buffer = ms.GetBuffer();
    Array.Clear(buffer, 0, buffer.Length);
    ms.Position = 0;
    ms.SetLength(0);
    ms.Capacity = 0; // <<< this one ******
}

I clicked on F12 to see Capacity Implementation, And I found this (I simplified generated code a little bit - I'm using Resharper):

public virtual int Capacity
{
  get
  { .... // some code }
  set
  {
    if ((long) value < this.Length) { // throw some ex }
    if (!this._isOpen) { // some another code }
    if (!this._expandable && value != this.Capacity) { //MemoryStreamNotExpandable }
    if (!this._expandable || value == this._capacity) return;
    if (value > 0)
    {
      byte[] numArray = new byte[value];
      if (this._length > 0)
        Buffer.InternalBlockCopy((Array) this._buffer, 0, (Array) numArray, 0, this._length);
      this._buffer = numArray;
    }
    else
      this._buffer = (byte[]) null; /// <<<< that's it! I need this one
    this._capacity = value;
  }
}

So It's clearing the Buffer, I'm not sure if this is correct or not!

Solution 4 - .Net

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser113476View Question on Stackoverflow
Solution 1 - .NetAndrew BezzubView Answer on Stackoverflow
Solution 2 - .NetRana IanView Answer on Stackoverflow
Solution 3 - .NetbunjeebView Answer on Stackoverflow
Solution 4 - .NetomglolbahView Answer on Stackoverflow