如何删除文本文件中的最后一行? [英] How to delete last line in a text file?

查看:522
本文介绍了如何删除文本文件中的最后一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

Therefore is there any methods or codes that I can utilize to delete the last line of the 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

推荐答案

类似的东西:

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

说明:

从技术上讲,您不会从文件中删除一行.您将读取文件的内容,然后将其写回,但不包括要删除的内容.

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.

此代码的作用是将所有行读入数组,并将这些行写回到文件中(仅最后一行除外). (Take()方法(LINQ的一部分)采用指定的行数,在本例中为length-1).在这里,var lines可以读为String[] lines.

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). Here, var lines can be read as String[] lines.

这篇关于如何删除文本文件中的最后一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆