Conditionaly strip the last line from a text file
Posted
by fraXis
on Stack Overflow
See other posts from Stack Overflow
or by fraXis
Published on 2010-05-21T20:43:30Z
Indexed on
2010/05/21
20:50 UTC
Read the original article
Hit count: 245
Hello,
I posted this yesterday on SO, and I received an answer that works great, but I need to change it around and I don't know how.
Here is my original message:
I need to strip the last line from a text file. I know how to open and save text files in C#, but how would I strip the last line of the text file?
The text file will always be different sizes (some have 80 lines, some have 20).
Can someone please show me how to do this?
Here is the code that someone gave me to do this (which works fine)
//Delete the last line from the file. This line could be 8174, 10000, or anything. This is from SO
string tempfile = @"C:\junk_temp.txt";
using (StreamReader reader2 = new StreamReader(newfilename))
{
using (StreamWriter writer2 = new StreamWriter(tempfile))
{
string line = reader2.ReadLine();
while (!reader2.EndOfStream)
{
writer2.WriteLine(line);
line = reader2.ReadLine();
} // by reading ahead, will not write last line to file
}
}
File.Delete(newfilename);
File.Move(tempfile, newfilename);
File.Delete(tempfile);
How would I change this to only delete the last line of the text file if it is a 4 or 5 digit string (such as 8001 or 99999).
If it is anything other than that, such as a %, then I don't want to delete the last line.
Can someone please modify the above code to do this for me?
Thanks so much.
© Stack Overflow or respective owner