foreach (string fileName in Directory.GetFiles("directoryName", "searchPattern")
{
string[] fileLines = File.ReadAllLines(fileName);
// Do something with the file content
}
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);
}
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;
}
}
}
// 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;
}
}
5条答案
按热度按时间3gtaxfhh1#
您也可以使用
File.ReadAllBytes()
或File.ReadAllText()
代替File.ReadAllLines()
,这取决于您的需求。0pizxfdo2#
这是一个基于LINQ的解决方案,它应该也能解决你的问题。它可能更容易理解和维护。所以如果你能使用LINQ给予试试吧。
dbf7pr2w3#
我想这就是你想要的。。
slsn1g294#
你好,实现你所要求的最简单的方法是这样的:
c0vxltue5#