Suedish
Suedish

Reputation: 385

(C#) How to read all files in a folder to find specific lines?

I'm very new to C# so please have some extra patience. What I am looking to do is read all files in a folder, to find a specific line (which can occur more than once in the same file) and get that output to show onscreen.

If anyone could point me in the direction to which methods I need to use it would be great. Thanks!

Upvotes: 2

Views: 3652

Answers (2)

Sergey Sirotkin
Sergey Sirotkin

Reputation: 1677

Start with

const string lineToFind = "blah-blah";
var fileNames = Directory.GetFiles(@"C:\path\here");
foreach (var fileName in fileNames)
{   
    int line = 1;     
    using (var reader = new StreamReader(fileName))
    {
         // read file line by line 
         string lineRead;
         while ((lineRead = reader.ReadLine()) != null)
         {
             if (lineRead == lineToFind)
             {
                 Console.WriteLine("File {0}, line: {1}", fileName, line);
             }
             line++;
         }
    }
}

As Nick pointed out below, you can make search parallel using Task Library, just replace 'foreach' with Parallel.Foreach(filesNames, file=> {..});

Directory.GetFiles: http://msdn.microsoft.com/en-us/library/07wt70x2

StreamReader: http://msdn.microsoft.com/en-us/library/f2ke0fzy.aspx

Upvotes: 7

Tim Schmelter
Tim Schmelter

Reputation: 460168

What output do you want to get on the screen?

If you want to find the first file with the given line, you can use this short code:

var firstMatchFilePath = Directory.GetFiles(@"C:\Temp", "*.txt")
                        .FirstOrDefault(fn => File.ReadLines(fn)
                                                  .Any(l => l == lineToFind));
if (firstMatchFilePath != null)
    MessageBox.Show(firstMatchFilePath);

I've used Directory.GetFiles with a search pattern to find all text files in a directory. I've used the LINQ extension methods FirstOrDefault and Any to find the first file with a given line.

Upvotes: 2

Related Questions