Search code examples
c#streamreaderfile.readalllines

c# search last key word .log file


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.


Solution

  • 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);
        }
    }