So I'm looking for a way to efficiently search for text in a file. Right now I'm using this:
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 1024, FileOptions.SequentialScan))
using (StreamReader streamReader = new StreamReader(fileStream))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
int index = 0;
while ((index = line.IndexOf(searchText, index, StringComparison.Ordinal)) != -1)
{
index += searchText.Length;
}
}
}
However, I was wondering if there was a way to more efficiently search the file. I was thinking of maybe searching for the text in buffers, but I'm not sure how. Thanks.
EDIT: Without calling IndexOf, I get around 1600ms. With index of, it's around 7400ms.
EDIT: I have a basic implementation of chunk reading, and it got the time down to 740ms. (No reading lines) It still has lots of work, but I basically read a chunk at a time and take index of.