如何从文件末尾截断 X 字节?
假设有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
FileStream.SetLength()
怎么样?What about
FileStream.SetLength()
?我只是简单地使用
而不是
SetLength
完美地工作,没有例外。文件确实被截断了。I am simply using
instead of
and
SetLength
works perfectly, no exception. The file is truncated indeed.让我们稍微封装一下:
let's encapsulate it a bit: