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

发布于 2024-09-13 10:47:10 字数 649 浏览 2 评论 0原文

假设有一个 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);

}

两者都打印 true!但它仍然抛出 NotSupportedException。有人知道如何处理这个问题吗?

Lets say there is a file which is 150 bytes long and I want to truncate the last 16 (or any number) of it from the end...

Is there any other way to do it than re writing the complete file?

UPDATE:
The SetLength should do the thing, but unfortunately NotSupportedException is thrown

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

}

Both print true! But still it throws a NotSupportedException. Anyone know how to handle this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘味果▽酱 2024-09-20 10:47:11

FileStream.SetLength() 怎么样?

What about FileStream.SetLength()?

南冥有猫 2024-09-20 10:47:11

我只是简单地使用

new FileStream(FileName, FileMode.Open)

而不是

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

SetLength 完美地工作,没有例外。文件确实被截断了。

I am simply using

new FileStream(FileName, FileMode.Open)

instead of

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

and SetLength works perfectly, no exception. The file is truncated indeed.

淡水深流 2024-09-20 10:47:11
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));
}
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);

let's encapsulate it a bit:

void TruncateEndFile(string path, int size)
{
    byte[] data = File.ReadAllBytes(path);
    File.WriteAllBytes(path, data.Take(data.Lenght - size));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文