Separate the last line from a text file

I need to remove the last line from a text file. I know how to open and save text files in C #, but how would I split the last line of a text file?

The text file will always have different sizes (some of them have 80 lines, some of them - 20).

Can someone please show me how to do this?

Thank.

+3
source share
2 answers

With a few lines you can 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 transfer data back and forth using 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);
+4
source

( ):

string[] lines = File.ReadAllLines(fileName);
Array.Resize(ref lines, lines.length - 1);
File.WriteAllLines(fileName, lines);
+3

Source: https://habr.com/ru/post/1746480/


All Articles