How to remove data from a MemoryStream

若如初见. 提交于 2019-12-05 07:21:50

You can't delete data from a MemoryStream - the cleanest would be to create a new memory stream based on the data you want:

MemoryStream ms = new MemoryStream(someData);
//ms.Position changes here
//...
byte[] data = ms.ToArray().Skip((int)ms.Position).ToArray();
ms = new MemoryStream(data);

This should work and be much more efficient than creating a new buffer:

byte[] buf = ms.GetBuffer();            
Buffer.BlockCopy(buf, numberOfBytesToRemove, buf, 0, (int)ms.Length - numberOfBytesToRemove);
ms.SetLength(ms.Length - numberOfBytesToRemove);

MemoryStream.GetBuffer() gives you access to the existing buffer, so you can move bytes around without creating a new buffer.

Of course you'll need to be careful about out-of-bounds issues.

Calling ms.SetLength(ms.Length - ms.Position) won't remove the bytes between 0 and ms.Position-1, in fact it will remove bytes between ms.Length - ms.Position and ms.Length.

Why not just write:

byte[] rest;
ms.Write(rest, ms.Length-ms.Position, rest.Length);
 var _ = new MemoryStream();
 _.Write(buf.GetBuffer(), (int)buf.Position, (int)buf.Length - (int)buf.Position);
 buf = _;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!