我有一个程序手动循环文件夹中的文件并搜索关键字,告诉你哪个文件有。
class Program
{
static void Main()
{
string input = "";
Console.WriteLine("Where? ");
input = Console.ReadLine();
LoopedData(input);
Console.ReadLine();
}
static void LoopedData(string path)
{
string[] files;
string[] directories;
string lineToFind = keyword;
files = Directory.GetFiles(path);
foreach (string file in files)
{
int line = 1;
using (var reader = new StreamReader(file))
{
// read file line by line
string lineRead;
while ((lineRead = reader.ReadLine()) != null)
{
if ( lineRead.Contains(lineToFind))
{
Console.WriteLine("File {0}, line: {1}", file, lineRead);
Console.ReadLine();
}
else
{
Console.WriteLine(" ");
}
line++;
}
}
Console.WriteLine("Finished.....");
Console.ReadLine();
//Console.WriteLine(file);
// look for string here
}
directories = Directory.GetDirectories(path);
foreach (string directory in directories)
{
// Process each directory recursively
LoopedData(directory);
}
}
}
我已经能够手动输入要搜索的文件夹,但是我很难为关键字创建类似的方法。我尝试在Main类中引用它,但没有成功。我需要一双新鲜的眼睛。
我尝试的任何搜索都不会产生有用的结果
答案 0 :(得分:1)
看来你已经知道该怎么做了。你正确地做了路径。要从用户那里获取keyword
,只需执行与路径相同的操作:
static void Main()
{
string path = "";
string keyword = "";
Console.WriteLine("Where? "); // read path
path = Console.ReadLine();
Console.WriteLine("What? "); // read keyword
keyword = Console.ReadLine();
LoopedData(input, keyword);
Console.ReadLine();
}
并更改LoopedData
这样的签名,将keyword
作为参数传递:
static void LoopedData(string path, string keywork)
{
// your code
}