简体   繁体   中英

(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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM