search text file using c# and display the line number and the complete line that contains the search keyword

Chitresh picture Chitresh · Mar 13, 2010 · Viewed 49.8k times · Source

I require help to search a text file (log file) using c# and display the line number and the complete line that contains the search keyword.

Answer

PeterM picture PeterM · Mar 13, 2010

This is a slight modification from: http://msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
    if ( line.Contains("word") )
    {
        Console.WriteLine (counter.ToString() + ": " + line);
    }

   counter++;
}

file.Close();