代码中有一些错误:
// 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);