Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - 如何删除文本文件中的最后一行?(How to delete last line in a text file?)

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.

(每当从第三方程序生成日志文件时,我都有一个简单的日志文本文件,扩展名为.txt,在该文本文件的末尾带有一个空格行。)

Therefore is there any methods or codes that I can utilize to delete the last line of the text file?

(因此,有什么方法或代码可用来删除文本文件的最后一行吗?)

An example of the log text file:

(日志文本文件的示例:)

Sun Jul 22 2001 02:37:46,73882,...b,r/rrwxrwxrwx,0,0,516-128-3,C:/WINDOWS/Help/digiras.chm
Sun Jul 22 2001 02:44:18,10483,...b,r/rrwxrwxrwx,0,0,480-128-3,C:/WINDOWS/Help/cyycoins.chm
Sun Jul 22 2001 02:45:32,10743,...b,r/rrwxrwxrwx,0,0,482-128-3,C:/WINDOWS/Help/cyzcoins.chm
Sun Jul 22 2001 04:26:14,174020,...b,r/rrwxrwxrwx,0,0,798-128-3,C:/WINDOWS/system32/spool/drivers/color/kodak_dc.icm
  ask by JavaNoob translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about something like :

(怎么样:)

var lines = System.IO.File.ReadAllLines("...");
System.IO.File.WriteAllLines("...", lines.Take(lines.Length - 1).ToArray());

Explanation:

(说明:)

Technically, you don't delete a line from a file.

(从技术上讲,您不会从文件中删除一行。)

You read the contents of a file and write them back excluding the content you want deleted.

(您读取文件的内容并将其写回,但不包括要删除的内容。)

What this code does is read all the lines into an array, and write these lines back to the file excluding only the last line.

(这段代码的作用是将所有行读入数组,并将这些行写回到文件中(仅最后一行除外)。)

(Take() method (Part of LINQ) takes number of lines specified which in our case, is length - 1).

((Take()方法(LINQ的一部分)采用指定的行数,在我们的示例中为length-1)。)

Here, var lines can be read as String[] lines .

(在这里, var lines可以读取为String[] lines 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...