如何删除文本文件中的最后一行?

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

因此,我可以使用任何方法或代码来删除文本文件的最后一行吗?

日志文本文件的示例:

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

说明:

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

这段代码的作用是将所有行读入一个数组,然后将这些行写回文件,只排除最后一行。 (Take()方法(LINQ的一部分)获取指定的行数,在我们的例子中,长度为1)。 这里, var lines可以读作String[] lines

使用此方法删除文件的最后一行:

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

编辑:已实现先前不存在的行变量,因此我更新了代码。

如果要从文件中删除最后N行而不将所有全部加载到内存中

 int numLastLinesToIgnore = 10; string line = null; Queue deferredLines = new Queue(); using (TextReader inputReader = new StreamReader(inputStream)) using (TextWriter outputReader = new StreamWriter(outputStream)) { while ((line = inputReader.ReadLine()) != null) { if (deferredLines.Count() == numLastLinesToIgnore) { outputReader.WriteLine(deferredLines.Dequeue()); } deferredLines.Enqueue(line); } // At this point, lines still in Queue get lost and won't be written } 

发生的情况是,您使用维度numLastLinesToIgnore缓存队列中的每个新行,并从其中弹出一行,以便仅在队列已满时写入。 实际上,您可以numLastLinesToIgnore 文件,并且可以在到达文件末尾之前停止numLastLinesToIgnore行, 而无需事先知道总行数

请注意,如果文本小于numLastLinesToIgnore ,则结果为空。

我想出了它作为镜像解决方案: 从文本文件中删除特定行?

您无法删除行结束,因为File.WriteAllLines会自动添加它,但是,您可以使用此方法:

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

这不是我的,我发现它在.NET File.WriteAllLines在文件末尾留下空行