C#C
C#3y ago
Pixel-ink

❔ [RESOLVED] Find all Occurrences in All Files in Folder Issue

I have this code that works, but it only returns one result per file if string exists in file.
And, I know that the "FirstOrDefault" is why I only get 1 returned result from one particular file.
This particular file has 22 lines that meet the find criteria>

Here is my issue.
I have Tried "All, and Any" and get error because they are bool conditions. Here is my line..
This code works but I need to know what else can I use instead of "FirstOrDefault" to return All my results that match my search criteria.
string occurrence = lines.FirstOrDefault(l => l.Contains("DateTime.Now"));

Any input on this small issue will be appreciated a lot.

string dirScanner = (GlobalVar.dataPath);
    if (string.IsNullOrWhiteSpace("DateTime.Now"))
        return;

        string[] allFiles = Directory.GetFiles(dirScanner, "*.cs");
        txtCode.Text = "";

        foreach (string file in allFiles)
        {
            string[] lines = File.ReadAllLines(file);
            **//string occurrence = lines.All(l => l.Contains("DateTime.Now"));  <<---- ERROR If I USE THIS LINE**
            string occurrence = lines.FirstOrDefault(l => l.Contains("DateTime.Now"));
            if (occurrence != null)
            {
                txtCode.Text = txtCode.Text + ">>> " + Path.GetFileName(file) + Environment.NewLine;
                txtCode.Text = txtCode.Text + occurrence + Environment.NewLine;
                txtCode.Text = txtCode.Text + "---------------------------------------------------------------" + Environment.NewLine;
            }
        }
Was this page helpful?