[英]Delete multiple lines from text file using c#
I have a text file containing 100 lines.我有一个包含 100 行的文本文件。 I want to delete first 20 lines from that file I have a following code
我想从该文件中删除前 20 行我有以下代码
IS anyone tell me how to do that?有人告诉我该怎么做吗? this code only deleting 1 line.
此代码仅删除 1 行。 I want to delete first 20 lines
我想删除前 20 行
string line = null;
int line_number = 0;
int line_to_delete = 12;
using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
while ((line = reader.ReadLine()) != null) {
line_number++;
if (line_number == line_to_delete)
continue;
writer.WriteLine(line);
}
}
}
How about using some Linq
and static
methods?使用一些
Linq
和static
方法怎么样? If performance is not crucial(the code will read all lines into memory):如果性能不重要(代码会将所有行读入内存):
File.WriteAllLines("outputfile",
File.ReadLines("inputfile").Skip(20));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.