2013-06-24 39 views
0

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

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

回答

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"); 
+0

这是字符串在日志文件中的样子:6/24/2013 6:36:25 AM 0 ProcessRecordFilingRequest中的异常:DexFlow.Framework.DXException:CM中的文档存储失败。 –

+0

如果实际格式与当前格式不同,您可以调整正则表达式模式。或者使用'DateTime.ParseExact' –

+0

这不会返回包含单词的任何内容。我错过了什么吗? –

0

如果你问你的代码是做什么的。它正在对CM失败+ ToString()进行检查,以确保日期时间对象的默认字符串转换在CM FAILED和CM之间没有空格。

是你的意图吗?