简体   繁体   English

从文件流中删除字节

[英]Deleting a byte from a filestream

How can I delete a byte if I have its offset from a FileStream and then rewrite it example: 如果我从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 .......

I tried this but failed : 我尝试了这个但是失败了:

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

Where va is equal to DB5 其中va等于DB5

There are some mistakes in the code: 代码中有一些错误:

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

However , that way of using the Read method is not reliable . 但是 ,使用Read方法的方法并不可靠 The method can actually read less bytes than you request. 比你请求的方法可以实际读取的字节 You need to use the return value from the method call, which is the number of bytes actually read, and loop until you have got the number of bytes that you need: 您需要使用方法调用的返回值,即实际读取的字节数,然后循环直到获得所需的字节数:

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