Thursday, April 28, 2011

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?

From stackoverflow
  • On linux (or other posix systems): truncate, ftruncate

  • 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));
    }
    
    Ranhiru Cooray : Thank you :) Although this will work, this will take complete file to memory, change it and then write it back... Isn't there a more efficient way of handling this?
    abatishchev : @Ranhiru: Not the best way, of course. I will think about something more effective
  • What about FileStream.SetLength()?

    Kevin Brock : I was about to add this. Link http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx
    Ranhiru Cooray : Thanx this should work :)
    Ranhiru Cooray : Unfortunately there is a `NotSupportedException` thrown when SetLength is used... But i checked, `CanSeek` and `CanRead` are both true... I don't know why it is Not Supported
    Gary : What about CanWrite?
    Ranhiru Cooray : Just checked...CanWrite is true as well. Please check the updated question

0 comments:

Post a Comment