Reputation:
If I have many text documents and one of them has the word that I'm looking for. So how can I search in all documents? like this
FileStream File = new FileStream(@"C:\Users\user\Desktop\input\file1.txt",
FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(File);
and I have file1,file2,....
Upvotes: 1
Views: 205
Reputation: 6103
You can use StreamReader to read the file line by line. This could reduce the memory consumption in case you have large files. Here is the sample code:
var searchText = "sometext";
var directory = @"C:\Users\user\Desktop\input";
foreach (var fileName in Directory.GetFiles(directory, "*.txt"))
{
using (var fileStream = File.OpenRead(fileName))
{
using (var streamReader = new StreamReader(fileStream))
{
string line;
var lineNum = 1;
while ((line = streamReader.ReadLine()) != null)
{
if (line.Contains(searchText))
{
Console.WriteLine($"Found {searchText} at line {lineNum}");
}
lineNum++;
}
}
}
}
Upvotes: 0
Reputation: 20373
First generate a collection of paths to search.
If this is file1, file2 etc. within the same directory then this will work:
int numberOfFiles = //...
string word = //...
var filesThatContainWord = Enumerable.Range(1, numberOfFiles)
.Select(i => $@"C:\Users\user\Desktop\input\file{i}.txt")
.Where(path => File.ReadLines(path).Any(line => line.Contains(word));
Using File.ReadLines
with Any
has the benefit of only reading each file until the specified word is found.
It is also memory efficient by not loading the entire file into memory.
This can be encapsulated into a method:
IEnumerable<string> ContainsWord(IEnumerable<string> paths, string word)
=> paths.Where(path => File.ReadLines(path).Any(line => line.Contains(word));
And called with any number of file paths.
For example:
var paths = ContainsWord(Directory.EnumerateFiles("YourDirectoryPath"), "word");
Upvotes: 0
Reputation: 5380
You need to loop files by Directory.GetFiles
and search for each .txt files as follows:
string directory = @"C:\Users\user\Desktop\input";
string searchText ="Search text";
string[] allFiles = Directory.GetFiles(directory, "*.txt");
foreach (string file in allFiles)
{
string[] lines = File.ReadAllLines(file);
if(lines.Any(l => l.Contains(searchText)))
{
//It means "Search text" is found in this file and do whatever you want
}
}
Upvotes: 2