除去一个文本文件的C#中的第一线 [英] Removing the first line of a text file in C#
问题描述
我可以使用当前删除一个文本文件的最后一行:
I can currently remove the last line of a text file using:
var lines = System.IO.File.ReadAllLines("test.txt");
System.IO.File.WriteAllLines("test.txt", lines.Take(lines.Length - 1).ToArray());
虽然,怎么可能来代替删除文本文件的开头?
Although, how is it possible to instead remove the beginning of the text file?
推荐答案
而不是 lines.Take
,您可以改用 lines.Skip
这样的:
Instead of lines.Take
you can instead use, lines.Skip
like:
var lines = File.ReadAllLines("test.txt");
File.WriteAllLines("test.txt", lines.Skip(1).ToArray());
在开始尽管事实上使用的技术(读取所有文本和所有内容写回到)是非常低效的截断。
to truncate at the beginning despite the fact that the technique used (read all text and write everything back) is very inefficient.
关于有效的方法:效率低下来自必要读取整个文件到内存中。周围的其他方法可以很容易地寻求一个流和数据流复制到另一个输出文件,删除原始,和重命名旧。那一个也同样快,但占用更少的内存。
About the efficient way: The inefficiency comes from the necessity to read the whole file into memory. The other way around could easily be to seek in a stream and copy the stream to another output file, delete the original, and rename the old. That one would be equally fast and yet consume much less memory.
截断一个文件到底是要容易得多。你可以只找到trunaction立场,并要求 FileStream.SetLength()
。
Truncating a file at the end is much easier. You can just find the trunaction position and call FileStream.SetLength()
.
这篇关于除去一个文本文件的C#中的第一线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!