我正在使用这个 foreach 循环来搜索目录中的文件,然后读取它们。
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
在此循环内,我想在文件中搜索包含单词“已发送”的行。有没有办法找到这个词然后读那一行?
最佳答案
试一试:
var location = @"<your location>";
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
{
var findedLines = File.ReadAllLines(file)
.Where(l => l.Contains("Sended"));
}
如果你处理大文件,你应该使用ReadLines方法,因为当你使用ReadLines时,你可以在返回整个集合之前开始枚举字符串集合;当您使用 ReadAllLines 时,您必须等待整个字符串数组被返回,然后才能访问该数组。
msdn 的另一个例子:
var files = from file in Directory.EnumerateFiles(location, "*.MAI")
from line in File.ReadLines(file)
where line.Contains("Sended")
select new
{
File = file,
Line = line
};
关于c# - 查看文件是否包含特定字符串,然后读取该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31044841/