views:

88

answers:

3

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?

A: 

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

Drakosha
+1  A: 
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));
}
abatishchev
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?
Ranhiru Cooray
@Ranhiru: Not the best way, of course. I will think about something more effective
abatishchev
+2  A: 

What about FileStream.SetLength()?

Gary
I was about to add this. Link http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx
Kevin Brock
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
Ranhiru Cooray
What about CanWrite?
Gary
Just checked...CanWrite is true as well. Please check the updated question
Ranhiru Cooray