如何从 MemoryStream 中删除数据
我无法让它发挥作用。我有一个 MemoryStream 对象。本班 有一个 Position 属性,可以告诉您已读取了多少字节。
我想要做的是删除 0 和 Position-1 之间的所有字节
我尝试过:
MemoryStream ms = ...
ms.SetLength(ms.Length - ms.Position);
但在某些时候我的数据被损坏了。
所以我最终这样做了,
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);
虽然有效,但效率并不高。
我有什么想法可以让它发挥作用吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该可行并且比创建新缓冲区更有效:
MemoryStream.GetBuffer() 使您可以访问现有缓冲区,因此您可以移动字节而无需创建新缓冲区。
当然,您需要小心越界问题。
This should work and be much more efficient than creating a new buffer:
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.
您无法从 MemoryStream 中删除数据 - 最干净的方法是根据您想要的数据创建一个新的内存流:
You can't delete data from a
MemoryStream
- the cleanest would be to create a new memory stream based on the data you want:调用
ms.SetLength(ms.Length - ms.Position)
不会删除0
和ms.Position-1
之间的字节,事实上,它将删除ms.Length - ms.Position
和ms.Length
之间的字节。为什么不直接写:
Calling
ms.SetLength(ms.Length - ms.Position)
won't remove the bytes between0
andms.Position-1
, in fact it will remove bytes betweenms.Length - ms.Position
andms.Length
.Why not just write: