How to delete last line in a text file?

前端 未结 6 905
一整个雨季
一整个雨季 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:20

    You can't delete the line end, as File.WriteAllLines automatically adds it, however, you can use this method:

    public static void WriteAllLinesBetter(string path, params string[] lines)
    {
        if (path == null)
            throw new ArgumentNullException("path");
        if (lines == null)
            throw new ArgumentNullException("lines");
    
        using (var stream = File.OpenWrite(path))
        using (StreamWriter writer = new StreamWriter(stream))
        {
            if (lines.Length > 0)
            {
                for (int i = 0; i < lines.Length - 1; i++)
                {
                    writer.WriteLine(lines[i]);
                }
                writer.Write(lines[lines.Length - 1]);
            }
        }
    }
    

    This is not mine, I found it at .NET File.WriteAllLines leaves empty line at the end of file

提交回复
热议问题