简体   繁体   中英

How do I truncate a file X bytes from the end?

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?

FileStream.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM