Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Bit late to the game on this one, but happened across this post and thought I'd add an alternative answer.

foreach (var match in File.ReadLines(@"c:\LogFile.txt")
                          .Select((text, index) => new { text, lineNumber = index+ 1 })
                          .Where(x => x.text.Contains("SEARCHWORD")))
{
    Console.WriteLine("{0}: {1}", match.lineNumber, match.text);
}

This uses:

  • File.ReadLines, which eliminates the need for a StreamReader, and it also plays nicely with LINQ's Where clause to return a filtered set of lines from a file.

  • The overload of Enumerable.Select that returns each element's index, which you can then add 1 to, to get the line number for the matching line.

Sample Input:

just a sample line
another sample line
first matching SEARCHWORD line
not a match
...here's aSEARCHWORDmatch
SEARCHWORD123
asdfasdfasdf

Output:

3: first matching SEARCHWORD line
5: ...here's aSEARCHWORDmatch
6: SEARCHWORD123

To export do Excel you can use the CSV file format, like the Pessimist wrote. If you are uncertain about what to write, try entering some data in MS Excel and click on "Save As" option in the Menu and choose CSV as file type.

Take care when writing a CSV file format as in some languages the default for separating values is not the comma. In brazilian portuguese, for example, the default is comma as decimal separator, dot as thousands separator and semicolon for separating values. Mind the culture when writing that.

The other alternative is using horizontal tabs as separators. Experiment to write a string, press the TAB key and then another string and paste it into Microsoft Excel. It is the default separator in that program.

If you're using an ad-hoc solution to your specific problem, either alternatives can be used without much thinking. If you are programming something to be used by other persons (or in other environments), mind the culture specific differences.

Oh, I've just remembered now: you can write a Spreadsheet using XML, you can do that with only the .NET package. I've done that years ago with C# .NET 2.0

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top