【问题标题】:c# search last key word .log file [closed]c#搜索最后一个关键字.log文件[关闭]
【发布时间】:2018-11-19 12:43:17
【问题描述】:

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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • file.ReadAllLines 和 StreamReader,但很难弄清楚如何读取关键字的最后一个实例并比较时间。
  • 您还应该提供一些用于比较DateTime 值的逻辑规范。
  • 如果您发布的问题只需要有人为您编写代码,您将很难在这里度过。我建议在下次发布之前阅读How to Ask
  • 感谢大家的帮助。我一定会再次通读如何提问页面。

标签: c# streamreader file.readalllines


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多