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
}
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);
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With