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 开发者_StackOverflow(some have 80 lines, some have 20).
Can someone please show me how to do this?
Thanks.
With a small number of lines, you could easily use something like this
string filename = @"C:\Temp\junk.txt";
string[] lines = File.ReadAllLines(filename);
File.WriteAllLines(filename, lines.Take(lines.Count() - 1));
However, as the files get larger, you may want to stream the data in and out with something like this
string filename = @"C:\Temp\junk.txt";
string tempfile = @"C:\Temp\junk_temp.txt";
using (StreamReader reader = new StreamReader(filename))
{
using (StreamWriter writer = new StreamWriter(tempfile))
{
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
writer.WriteLine(line);
line = reader.ReadLine();
} // by reading ahead, will not write last line to file
}
}
File.Delete(filename);
File.Move(tempfile, filename);
For small files, an easy way (although far from the most efficient) would be:
string[] lines = File.ReadAllLines(fileName);
Array.Resize(ref lines, lines.length - 1);
File.WriteAllLines(fileName, lines);
精彩评论