读取文件,删除包含单词'bad'的行,将文件写入新文件。 [英] Read a file, remove line containing word 'bad', write the file to a new file.
本文介绍了读取文件,删除包含单词'bad'的行,将文件写入新文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将一个大文本文件读到一个列表,然后搜索包含单词'bad'的行。如何在没有该行的情况下将文件写回新文件?
I am reading a large text file to a list then searching for the line that contains the word 'bad'. How do I write the file without that line back to a new file?
这是我的代码;
namespace ReadAndWriteFile
{
class Program
{
static void Main(string[] args)
{
List<string> theWholeFile = File.ReadLines(@"C:\Users\Desktop\Current Projects\ReadAndWriteFile\ReadAndWriteFile\bin\Debug\01Aug.txt").Reverse().Take(5).ToList();
foreach (string line in theWholeFile)
{
if ( line.Contains("bad"))
{
theWholeFile.Remove(line);
File.WriteAllLines(@"C:\Users\Public\Success", theWholeFile.ToArray());
}
}
Console.Read();
}
}
}
推荐答案
试试这个:
File.WriteAllLines( @"C:\...\OutputFile.txt", File.ReadLines( @"C:\...\InputFile.txt" ).Where( s => !Regex.IsMatch( s, @"\bbad\b" ) ) );
删除包含"bad"的所有行。
It remove all of the lines that contain "bad".
这篇关于读取文件,删除包含单词'bad'的行,将文件写入新文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文