如何从末尾截断文件X字节?

时间:2010-08-04 06:32:18

标签: c# file-io compact-framework filestream truncate

假设有一个150字节长的文件,我想从最后截断它的最后16个(或任何数字)...

除了重新编写完整的文件之外,还有其他方法吗?

更新 SetLength应该做的事情,但不幸的是抛出了NotSupportedException

using (FileStream fsFinalWrite = new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{

  fsFinalWrite.Seek(16, SeekOrigin.End);

  fsFinalWrite.Write(SwappedBytes, 0, 16);

  Debug.WriteLine("fsFinalWrite Can Seek = " + fsFinalWrite.CanSeek);
  Debug.WriteLine("fsFinalWrite Can Write = " + fsFinalWrite.CanWrite);

  fsFinalWrite.SetLength((long)lengthOfFile);

}

两者都是真的!但它仍会抛出NotSupportedException。任何人都知道如何处理这个?

3 个答案:

答案 0 :(得分:11)

FileStream.SetLength()怎么样?

答案 1 :(得分:1)

我只是在使用

new FileStream(FileName, FileMode.Open)

而不是

new FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)

SetLength完美无缺,也不例外。该文件确实被截断了。

答案 2 :(得分:0)

using System.IO;    
using System.Linq; // as far as you use CF 3.5, it should be available

byte[] bytes = File.ReadAllBytes(path);
byte[] trancated = bytes.Take(bytes.Lenght - 15);
File.WriteAllBytes(path, trancated);

让我们把它封装一下:

void TruncateEndFile(string path, int size)
{
    byte[] data = File.ReadAllBytes(path);
    File.WriteAllBytes(path, data.Take(data.Lenght - size));
}