How to use C# Extension Method to Filter Lines in Text Files

Working with log files or large text datasets? You’ll often need to search for lines containing specific keywords like "ERROR" or "WARNING". Instead of repeating the same logic, a C# Extension Method to Filter Lines offers a clean, reusable solution.

This post walks you through a memory-efficient, scalable approach using this custom method—applicable to both individual files and entire directories.

Why Use an Extension Method?

An extension method in C# lets you “extend” an existing type (like FileInfo) with new functionality without modifying the original class. This improves readability and reuse.

Here’s a clean and efficient implementation with C# Extension Method to Filter Lines :

using System;
using System.Collections.Generic;
using System.IO;

public static class FileExtensions
{
    public static IEnumerable ReadAndFilter(this FileInfo info, Predicate condition)
    {
        if (info == null || condition == null)
            throw new ArgumentNullException();

        using var reader = new StreamReader(info.FullName);
        string? line;
        while ((line = reader.ReadLine()) != null)
        {
            if (condition(line))
            {
                yield return line;
            }
        }
    }
}


Highlights:

  • yield return is used to stream results—great for large files.
  • Uses a Predicate<string> so you can pass any custom condition.
  • Wrapped with basic null checking for safety.

Let’s say you want to find all lines containing the word "ERROR" in a specific file:

string FilePath = "C:\\logs\\app.log";
string SearchString = "ERROR";

var result = new FileInfo(FilePath).ReadAndFilter(s => s.Contains(SearchString));
foreach (var line in result)
{
    Console.WriteLine(line);
}

You can extend this logic to scan all .txt files in a folder:

string path = "C:\\logs";

foreach (string file in Directory.GetFiles(path, "*.txt"))
{
    var result = new FileInfo(file).ReadAndFilter(s => s.Contains(SearchString));
    foreach (string line in result)
    {
        Console.WriteLine($"[{Path.GetFileName(file)}] {line}");
    }
}

(Visited 256 times, 1 visits today)