I would consider two approaches, for large file (megabytes) and for relatively small.
Large File
If file is large and contains megabytes of data: use stream reader, read file untile EndOfLine, analize just readed string
string pattern = "england";
IList<string> result = new List<string>();
using (var reader = new StreamReader("TestFile.txt"))
{
string currentLine;
while ((currentLine= reader.ReadLine()) != null)
{
if (currentLine.Contains(pattern)
{
// if you do not need multiple lines and just the first one
// just break from the loop (break;)
result.Add(currentLine);
}
}
}
Small file
If a file is small you can use helper which returns all file content as array of strings - (File.ReadAllLines()) string per line and then use LINQ to search for substring. if you are using .NET 4
or newer you can leverage new helper (File.ReadLines()) which does not read entire file and does read as deffered operation.
.NET 2.0 - 3.5:
string pattern = "england";
IEnumerable<string> result = File.ReadAllLines()
.Where(l => l.Contains(pattern));
.NET4 - 4.5:
string pattern = "england";
IEnumerable<string> result = File.ReadLines()
.Where(l => l.Contains(pattern));
if you need just the first line use .FirstOrDefault(l => l.Contains(pattern))
instead of Where(l => l.Contains(pattern))
MSDN:
The ReadLines and ReadAllLines methods differ as follows: When you use
ReadLines, you can start enumerating the collection of strings before
the whole collection is returned; when you use ReadAllLines, you must
wait for the whole array of strings be returned before you can access
the array. Therefore, when you are working with very large files,
ReadLines can be more efficient.