繁体   English   中英

从文件流中删除字节

[英]Deleting a byte from a filestream

如果我从FileStream偏移了字节,如何删除它,然后重写它,例如:

Offset  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
DB0     00 00 00 00 00 00 01(byte to delete) 00 .......

我尝试了这个但是失败了:

byte[] newFile = new byte[fs.Length];
fs.Position = 0;
fs.Read(newFile, 0, va -1);
fs.Position = va + 1;
fs.Read(newFile, 0, va + 1);
fs.Close();
fs.Write(newFile, 0, newFile.Length);

其中va等于DB5

代码中有一些错误:

// the buffer should be one byte less than the original file
byte[] newFile = new byte[fs.Length - 1];
fs.Position = 0;
// you should read "va" bytes, not "va-1" bytes
fs.Read(newFile, 0, va);
fs.Position = va + 1;
// you should start reading into positon "va", and read "fs.Length-va-1" bytes
fs.Read(newFile, va, fs.Length - va - 1);
fs.Close();
fs.Write(newFile, 0, newFile.Length);

但是 ,使用Read方法的方法并不可靠 比你请求的方法可以实际读取的字节 您需要使用方法调用的返回值,即实际读取的字节数,然后循环直到获得所需的字节数:

byte[] newFile = new byte[fs.Length - 1];
fs.Position = 0;
int pos = 0;
while (pos < va) {
  int len = fs.Read(newFile, pos, va - pos);
  pos += len;
}
fs.Position = va + 1;
int left = fs.Length - 1;
while (pos < left) {
  int len = fs.Read(newFile, pos, left - pos);
  pos += len;
}
fs.Close();
fs.Write(newFile, 0, newFile.Length);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM