How to remove data from a MemoryStream

2019-05-03 06:50发布

I cannot get this to work. I have a MemoryStream object. This class has a Position property that tells you how many bytes you have read.

What I want to do is to delete all the bytes between 0 and Position-1

I tried this:

MemoryStream ms = ...
ms.SetLength(ms.Length - ms.Position);

but at some point my data gets corrupted.

So I ended up doing this

MemoryStream ms = ...
byte[] rest = new byte[ms.Length - ms.Position];
ms.Read(rest, 0, (int)(ms.Length - ms.Position));
ms.Dispose();
ms = new MemoryStream();
ms.Write(rest, 0, rest.Length);

which works but is not really efficient.

Any ideas how I can get this to work?

Thanks

4条回答
ら.Afraid
2楼-- · 2019-05-03 07:27

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);
查看更多
家丑人穷心不美
3楼-- · 2019-05-03 07:45

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);
查看更多
在下西门庆
4楼-- · 2019-05-03 07:46

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.

查看更多
混吃等死
5楼-- · 2019-05-03 07:49
 var _ = new MemoryStream();
 _.Write(buf.GetBuffer(), (int)buf.Position, (int)buf.Length - (int)buf.Position);
 buf = _;
查看更多
登录 后发表回答