C# Extension method: Searching lines containing specific string

  • Post author:
  • Post category:C#
  • Reading time:1 mins read

Searching for lines in text file containing a specific string can be very handy with below code snippet. This method is very optimal specially if we are accessing log/error/access files.

public static IEnumerable<string> ReadAndFilter(this FileInfo info, Predicate<string> condition)
    {
        string line;
        using (var reader = new StreamReader(info.FullName))
        {
            while ((line = reader.ReadLine()) != null)
            {
                if (condition(line))
                {
                    yield return line;
                }
            }
        }
    }

Usage:

//FilePath is a string variable containing path of file
//SearchString is string to be searched
var result = new FileInfo(FilePath).ReadAndFilter(s => s.Contains(SearchString));

The method can be further improvised to search lines in text files with in a directory containing the specific string.

foreach (string file in Directory.GetFiles(path, "*.txt").Select(Path.GetFullPath))
        {
            var result = new FileInfo(file).ReadAndFilter(s => s.Contains(SearchString));
            foreach (string line in result)
            {
                .....
                .....
            }
        }
(Visited 252 times, 1 visits today)