Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get/delete last character of file without loading into memory

Tags:

c#

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
  }
like image 263
Deniz Zoeteman Avatar asked Jan 30 '26 06:01

Deniz Zoeteman


2 Answers

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);
like image 90
Douglas Avatar answered Jan 31 '26 19:01

Douglas


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 );
        }
like image 39
Felix Henke Avatar answered Jan 31 '26 20:01

Felix Henke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!