Reset or Clear .NET MemoryStream

▼魔方 西西 提交于 2019-11-29 10:32:05

问题


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?


回答1:


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.




回答2:


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

memoryStream.SetLength(0);



回答3:


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.



来源:https://stackoverflow.com/questions/2462391/reset-or-clear-net-memorystream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!