从文件流中删除一个字节

时间:2012-10-27 16:39:19

标签: c# 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

1 个答案:

答案 0 :(得分:1)

代码中存在一些错误:

// 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方法的方式不可靠。该方法实际上可以读取 less 字节而不是您请求的字节。您需要使用方法调用的返回值,即实际读取的字节数,并循环,直到获得所需的字节数:

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