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

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();

Leave a Comment