How to delete last line in a text file?
每当从第三方程序生成日志文件时,我都有一个简单的日志文本文件,扩展名为.txt,在该文本文件的末尾带有一个空格行。
因此,有什么方法或代码可用来删除文本文件的最后一行吗?
日志文本文件的示例:
1 2 3 4 | 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 |
怎么样:
1 2 | var lines = System.IO.File.ReadAllLines("..."); System.IO.File.WriteAllLines("...", lines.Take(lines.Length - 1).ToArray()); |
说明:
从技术上讲,您不会从文件中删除一行。您读取文件的内容并将其写回,但不包括要删除的内容。
这段代码的作用是将所有行读入数组,并将这些行写回到文件中(仅最后一行除外)。 (Take()方法(LINQ的一部分)采用指定的行数,在我们的示例中为length-1)。在这里,
使用此方法删除文件的最后一行:
1 2 3 4 5 6 7 | public static void DeleteLastLine(string filepath) { List<string> lines = File.ReadAllLines(filepath).ToList(); File.WriteAllLines(filepath, lines.GetRange(0, lines.Count - 1).ToArray()); } |
编辑:意识到行变量以前不存在,所以我更新了代码。
您无法删除行尾,因为File.WriteAllLines会自动添加它,但是,您可以使用以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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中找到它,在文件末尾留空行
如果要从文件中删除最后N行而不将所有行都加载到内存中,请执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | int numLastLinesToIgnore = 10; string line = null; Queue<string> deferredLines = new Queue<string>(); 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 } |
发生的情况是,您在维度为
请注意,如果文本小于
我想到了它作为镜像解决方案:
从文本文件中删除特定行?