How to delete last line in a text file?

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

    I just find a solution from other website, and this is the url https://stackoverrun.com/cn/q/627722 .

    With a small number of lines, you could easily use something like this

    string filename = @"C:\Temp\junk.txt";
    string[] lines = File.ReadAllLines(filename);
    

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

提交回复
热议问题