How to delete last line in a text file?

前端 未结 6 902
一整个雨季
一整个雨季 2020-12-11 02:30

I have a simple log text file with the extension of .txt with a white space line at the end of that text file every time the log file is generated from a 3rd party program.<

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 03:19

    Use this method to remove the last line of the file:

    public static void DeleteLastLine(string filepath)
    {
        List lines = File.ReadAllLines(filepath).ToList();
    
        File.WriteAllLines(filepath, lines.GetRange(0, lines.Count - 1).ToArray());
    
    }
    

    Edit: Realized the lines variable didn't exist previously, so I updated the code.

提交回复
热议问题