3

How can I get the last character in a file, and if it is a certain character, delete it without loading the entire file into memory?

This is what I have so far.

using (var fileStream = new FileStream("file.txt", FileMode.Open, FileAccess.ReadWrite)){
  fileStream.Seek(-1, SeekOrigin.End);
  if (Convert.ToChar(fileStream.ReadByte()) == ']')
  {
    // Here to come deleting the character
  }
Deniz Zoeteman
  • 9,691
  • 26
  • 70
  • 97
  • 1
    Define "character". What kind of encoding does the file have? – Lasse V. Karlsen Aug 09 '14 at 15:49
  • 1
    It is easy to do for a byte. A character is much more complicated, it depends how the text in the file is encoded. One character can take between 1 and 5 bytes. Assuming you know how to deal with this somehow, basic calls are FileStream.Seek() and FileStream.SetLength(). – Hans Passant Aug 09 '14 at 15:54
  • I have added what I have so far. I found out just how to seek, but not sure how to delete the character in place. The character in question is']' as shown in the code I have. – Deniz Zoeteman Aug 09 '14 at 15:55

2 Answers2

10

If your text file is encoded as ASCII or UTF-8 (in which ] would be stored as a single byte), then you could just trim your file by one byte:

if (fileStream.ReadByte() == ']')
    fileStream.SetLength(fileStream.Length - 1);
Douglas
  • 53,759
  • 13
  • 140
  • 188
4

You can set the Position of a Filestream to the last byte and look what it is. Then use Douglas Solution to delete it:

using( FileStream fs = new FileStream( filePath, FileMode.Open ) )
        {
            fs.Position = fs.Seek( -1, SeekOrigin.End );
            if(fs.ReadByte() == ']' )
               fs.SetLength( fs.Length - 1 );
        }