1

I am trying to search through a text /.log file for the key word "DEBUG 2018-06-04T13:27:15+00:00" Once the last key word DEBUG is found, I would then like to compare the date and time to current date $ time and if older than 10 minutes output fail.

Ettienne
  • 23
  • 3
  • 3
    What have you tried so far? – Max von Hippel Jun 09 '18 at 19:35
  • file.ReadAllLines and StreamReader, but struggling to figure out how to read the last instance of the key word and compare the time. – Ettienne Jun 09 '18 at 19:41
  • You should also provide some specifications on the logic used to compare the `DateTime` values. – Jimi Jun 09 '18 at 19:43
  • You will have hard times here if you post questions where you just requires someone to write code for you. I suggest to read [ask] before posting nexttime – Steve Jun 09 '18 at 19:43
  • Thank you everyone for all the help. I will be sure to read through the How to Ask page again. – Ettienne Jun 10 '18 at 19:11

1 Answers1

2

You can extract all the matching substrings with Regex.Matches:

String text = File.ReadAllText(@"C:\My\File\Path.txt");

MatchCollection matches = Regex.Matches(
    text,
    @"DEBUG (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2})"
)

Inspect the last match:

if (matches.Count > 0) {
    Match last = matches[matches.Count - 1];
    DateTime dt = DateTime.Parse(last.Groups[1].Value);

    if (DateTime.Now > dt.AddMinutes(10)) {
         Console.WriteLine("Last date entry is older than 10 minutes ago: {0}", dt);
    }
}

Or loop through all matches:

foreach (Match match in matches) {
    // Parse the date string in the matched text:
    DateTime dt = DateTime.Parse(match.Groups[1].Value);

    if (DateTime.Now > dt.AddMinutes(10)) {
        // Date is older than 10 minutes ago
        Console.WriteLine("Date is older than 10 minutes ago: {0}", dt);
    }
}
jspcal
  • 50,847
  • 7
  • 72
  • 76