Strip the last line from a text file

2019-02-19 03:07发布

问题:

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.

回答1:

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);


回答2:

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);


标签: c# text stream