c# 搜索最后一个关键字.log 文件

c# search last key word .log file

我正在尝试在文本 /.log 文件中搜索关键字 "DEBUG 2018-06-04T13:27:15+00:00" 找到最后一个关键字 DEBUG 后,我想将日期和时间与当前日期 $ time 进行比较,如果早于 10 分钟,则输出失败。

您可以使用 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})"
)

检查最后一场比赛:

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

或遍历所有匹配项:

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