如何从MemoryStream中删除数据 [英] How to remove data from a MemoryStream

查看:110
本文介绍了如何从MemoryStream中删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使它正常工作.我有一个MemoryStream对象.这个班 有一个Position属性,可以告诉您已读取了多少字节.

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.

我要删除的是0到Position-1之间的所有字节

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

我尝试过:

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

但是在某些时候我的数据已损坏.

but at some point my data gets corrupted.

所以我最终这样做了

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);

有效,但效率不高.

有什么想法可以使它正常工作吗?

Any ideas how I can get this to work?

谢谢

推荐答案

您不能从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:

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

这篇关于如何从MemoryStream中删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆