【问题标题】:How do I truncate a file X bytes from the end?如何从末尾截断文件 X 字节?
【发布时间】:2010-08-04 06:32:18
【问题描述】:

假设有一个 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。有人知道如何处理吗?

【问题讨论】:

  • 操作系统?文件系统?

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


【解决方案1】:

FileStream.SetLength() 呢?

【讨论】:

  • 我正要添加这个。链接msdn.microsoft.com/en-us/library/…
  • 不幸的是,使用 SetLength 时会抛出 NotSupportedException ......但我检查了,CanSeekCanRead 都是真的......我不知道为什么它不支持
  • 刚刚检查过...CanWrite 也是如此。请检查更新的问题
  • 对于任何感兴趣的人,SetLength() 被声明为 Stream 基类上的(抽象)方法,因此任何其他体面的 Stream 子类理论上也应该提供截断其数据的实现这边走。 (我正在使用 MemoryStream,我很好奇是否可以应用相同的方法)。
【解决方案2】:

我只是在使用

new FileStream(FileName, FileMode.Open)

而不是

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

SetLength 完美运行,也不例外。文件确实被截断了。

【讨论】:

    【解决方案3】:
    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));
    }
    

    【讨论】:

    • 谢谢 :) 虽然这会起作用,但这会将完整的文件存储到内存中,对其进行更改,然后将其写回......难道没有更有效的方法来处理这个问题吗?
    • @Ranhiru:当然不是最好的方法。我会考虑一些更有效的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多