这就是我想要做的事情:
我想实现的想法是:
选择目录,然后输入字符串。转到该文件夹中的每个文件。例如,文件夹是:Directory={file1.txt,file2.txt,file3.txt}
我想首先去找file1.txt,将所有文本读成字符串,看看我的字符串是否在该文件中。如果是:请转到file2.txt,依此类推。
答案 0 :(得分:13)
foreach (string fileName in Directory.GetFiles("directoryName", "searchPattern")
{
string[] fileLines = File.ReadAllLines(fileName);
// Do something with the file content
}
您也可以使用File.ReadAllBytes()
或File.ReadAllText()
代替File.ReadAllLines()
,这取决于您的要求。
答案 1 :(得分:4)
var searchTerm = "SEARCH_TERM";
var searchDirectory = new System.IO.DirectoryInfo(@"c:\Test\");
var queryMatchingFiles =
from file in searchDirectory.GetFiles()
where file.Extension == ".txt"
let fileContent = System.IO.File.ReadAllText(file.FullName)
where fileContent.Contains(searchTerm)
select file.FullName;
foreach (var fileName in queryMatchingFiles)
{
// Do something
Console.WriteLine(fileName);
}
这是一个基于LINQ的解决方案,它也可以解决您的问题。它可能更容易理解,也更容易维护。所以,如果你能够使用LINQ试一试。
答案 2 :(得分:0)
我认为这就是你想要的......
string input = "blah blah";
string file_content;
FolderBrowserDialog fld = new FolderBrowserDialog();
if (fld.ShowDialog() == DialogResult.OK)
{
DirectoryInfo di = new DirectoryInfo(fld.SelectedPath);
foreach(string f in Directory.GetFiles(fld.SelectedPath))
{
file_content = File.ReadAllText(f);
if (file_content.Contains(input))
{
//string found
break;
}
}
}
答案 3 :(得分:0)
实现你所要求的最简单方法就是这样:
string[] Files = System.IO.Directory.GetFiles("Directory_To_Look_In");
foreach (string sFile in Files)
{
string fileCont = System.IO.File.ReadAllText(sFile);
if (fileCont.Contains("WordToLookFor") == true)
{
//it found something
}
}
答案 4 :(得分:0)
// Only get files that are text files only as you want only .txt
string[] dirs = Directory.GetFiles("target_directory", "*.txt");
string fileContent = string.Empty;
foreach (string file in dirs)
{
// Open the file to read from.
fileContent = File.ReadAllText(file);
// alternative: Use StreamReader to consume the entire text file.
//StreamReader reader = new StreamReader(file);
//string fileContent = reader.ReadToEnd();
if(fileContent.Contains("searching_word")){
//do whatever you want
//exit from foreach loop as you find your match, so no need to iterate
break;
}
}