Strip the last line from a text file

2019-02-19 02:49发布

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?

Thanks.

标签: c# text stream
2条回答
甜甜的少女心
2楼-- · 2019-02-19 03:19

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);
查看更多
【Aperson】
3楼-- · 2019-02-19 03:31

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);
查看更多
登录 后发表回答