C#Winform从文本文本中读取时间戳

时间:2013-06-24 13:12:49

标签: c# winforms

我需要从文件中读取时间戳,然后回顾过去30分钟,看看是否显示关键字“CM failed”。即使应用程序正在运行,这也是一个不断更新的日志文件。有任何想法吗?下面提供的代码回顾过去30,但我不确定它正在看什么时间。

TimeSpan ts = TimeSpan.FromMinutes(30);
//fake file which is opened using Notepad++
string temp = @"C:\Temp\efilelog.txt"; 

private void Form1_Load(object sender, EventArgs e)
{
     string str = File.ReadAllText(temp);

     Regex reg = new Regex("CM failed" + DateTime.Now.Subtract(ts));

     Match mat = reg.Match(str);

     // Get the creation time of a well-known directory.
     //DateTime dt = File.GetLastWriteTime(file);
     //Console.WriteLine("The last write time for this file was {0}.", dt, ts);

     if (mat.Success)
     {
         //send email which I already have functional
     }

     this.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

如果你问你的代码是做什么的。它正在检查CM FAILED +一个ToString()默认字符串转换你的datetime对象,CM FAILED和它之间没有空格。

这是你的意图吗?

答案 1 :(得分:0)

您需要解析文件中的上次失败时间,并检查该日期是否在过去30分钟内。假设您正在写这样的失败时间:

using (var writer = File.AppendText("efilelog.txt"))            
    writer.WriteLine("CM failed {0}", DateTime.Now.ToString());

然后,您将需要以下查询和正则表达式来获取上次失败时间:

Regex regex = new Regex("CM failed(?<time>.+)");
var lastFailTime = File.ReadLines("efilelog.txt")
                       .Select(line => regex.Match(line))
                       .Where(m => m.Success) // take only matched lines
                       .Select(m => DateTime.Parse(m.Groups["time"].Value))
                       .DefaultIfEmpty() // DateTime.Min if no failures
                       .Max();

然后检查30分钟内是否失败:

TimeSpan span = TimeSpan.FromMinutes(30);
if (span > DateTime.Now - lastFailTime)
    // alert 

根据您的新要求,您应该使用以下正则表达式:

Regex regex = new Regex("(?<time>.+(AM|PM)).*CM failed");