Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the last line of a StreamWriter?

I know that when we use a StreamWriter this is, by definition, to write in it but the fact is that at some point I can have the obligation to delete the last line of my streamwriter...

I found the following code (on SO) that works well :

var lines = System.IO.File.ReadAllLines(pluginQmlFileName);
System.IO.File.WriteAllLines(pluginQmlFileName, lines.Take(lines.Length - 1).ToArray());

but the thing is that I can't use it in my :

using (StreamWriter sw = new StreamWriter(pluginQmlFileName, true))
{
    [...]
}

section.

Is there a way to delete the last line in the using {} section or do I have to keep my actual code ?

like image 680
Guillaume Slashy Avatar asked Oct 16 '25 00:10

Guillaume Slashy


2 Answers

I don't think that a StreamWriter allows you to do this, but perhaps you could make your own stream wrapper which implements this behavior? That is, it would keep the last line in memory and only write it out when another line comes in.

like image 78
Vilx- Avatar answered Oct 17 '25 13:10

Vilx-


You could just remove the last line after reading in them all:

var lines = System.IO.File.ReadLines(pluginQmlFileName);

// will need changing to remove from the array if using ReadAllLines instead of ReadLines
lines = lines.RemoveAt(lines.Count - 1);
like image 36
Lloyd Powell Avatar answered Oct 17 '25 14:10

Lloyd Powell