我对C#很新,所以请多加耐心。我要做的是读取文件夹中的所有文件,找到一个特定的行(可以在同一个文件中多次出现)并将该输出显示在屏幕上。
如果有人能指出我需要使用哪种方法,那就太棒了。 谢谢!
答案 0 :(得分:5)
从
开始const string lineToFind = "blah-blah";
var fileNames = Directory.GetFiles(@"C:\path\here");
foreach (var fileName in fileNames)
{
int line = 1;
using (var reader = new StreamReader(fileName))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if (lineRead == lineToFind)
{
Console.WriteLine("File {0}, line: {1}", fileName, line);
}
line++;
}
}
}
正如尼克在下面指出的那样,你可以使用任务库进行并行搜索,只需用Parallel.Foreach替换'foreach'(filesNames,file => {..});
Directory.GetFiles:http://msdn.microsoft.com/en-us/library/07wt70x2
StreamReader:http://msdn.microsoft.com/en-us/library/f2ke0fzy.aspx
答案 1 :(得分:2)
您想要在屏幕上显示哪些输出?
如果要查找具有给定行的第一个文件,可以使用以下短代码:
var firstMatchFilePath = Directory.GetFiles(@"C:\Temp", "*.txt")
.FirstOrDefault(fn => File.ReadLines(fn)
.Any(l => l == lineToFind));
if (firstMatchFilePath != null)
MessageBox.Show(firstMatchFilePath);
我使用Directory.GetFiles
和搜索模式来查找目录中的所有文本文件。我已经使用LINQ扩展方法FirstOrDefault
和Any
来查找具有给定行的第一个文件。