Vans
Vans

Reputation: 115

Find specific file by last modified date and text inside the file

I must find file with last modified date and containing specific text pattern on line 3 of the file.

var directory = new DirectoryInfo("D:\\test");
var dispenser = directory.GetFiles("Dispenser*")
                         .OrderByDescending(f => f.LastWriteTime)
                         .First();
dispenser.CopyTo("..\\..\\Dispenser", true);
dispenserCopy = true;

This returns first file that has filename starting with 'Dispenser' and last modified date. How can I check if on line 3 it has specific text? And if it does not - check the next 'Dispenser*' file (by descending modified date) and so on, and so on, until there is one with text on line 3?

Thanks!

Upvotes: 0

Views: 556

Answers (1)

decPL
decPL

Reputation: 5402

EDIT: edited to attempt to match what I believe you're trying to achieve. That being said - in your place I would honestly take a step back and rethink the approach of using string operations on fixed line numbers against XML data.

var dispenser =
   directory.GetFiles("Dispenser*")
            .OrderByDescending(f => f.LastWriteTime)
            .Where(f => (File.ReadLines(f.FullName)
                             .Skip(2)
                             .FirstOrDefault()
                               ?? String.Empty).Contains("MY_EXPECTED_LINE"))
            .FirstOrDefault();

Upvotes: 2

Related Questions