0

如果我从 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

4

1 回答 1

2

代码中有一些错误:

// 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);
于 2012-10-27T16:50:24.860 回答