1

我正在使用 C#将日志写入本地位置 (C:\temp\log.txt)的文本文件中。文本文件存储如下

 2011-11-17 23:05:17,266 [6] FATAL Application

 2011-11-17 23:05:18,094 [6] FATAL Service

 2011-11-17 23:17:08,862 [6] FATAL Receipts - SaveReceipts
 System.InvalidOperationException: Sequence contains no elements
 at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
 at GID.AAFramework.EntityWrapper.ReceiptFacade.SaveReceipts(IEnumerable`1 records,     String user) in     c:\AdvancedAnalyticsProjects\Surya\Trunk\dotnet_src\GID.AAFramework.EntityWrapper\ReceiptFacade.cs:line 632

现在我想读取这个文件并想记录第一次输入的日期最后一个日期

如何在此文本文件中获取第一次日期和最后一次更新日期?

现在我正在使用以下代码阅读此文本文件:

StreamReader sr = new StreamReader(FileLocation);
if (sr != null)
{
  linelist.Add(sr.ReadToEnd());
  LogInfoByDate.Add(FileLocation, "StartDate:" + linelist.First().Substring(0, 10) + "|" + "EndDate:" + linelist.Last().Substring(0, 10));               
}

如果异常行是单行,我编写的这段代码用于获取第一次日期和最后更新日期,但它不适用于如上所示的多行异常。现在这是我的问题。谁能告诉我如何在这个文本文件中取第一个和最后一个日期?

4

2 回答 2

8

这是使用 LINQ 和的方法DateTime.TryParseExact

DateTime d = DateTime.Now;
var format = "yyyy-MM-dd HH:mm:ss,fff";
var fileDates = System.IO.File.ReadAllLines(path)
                .Where(l => l.Length >= format.Length
                        && DateTime.TryParseExact(l.Substring(0, format.Length)
                                                , format
                                                , CultureInfo.InvariantCulture
                                                , DateTimeStyles.None
                                                , out d)
                )
                .Select(l => d)
                .OrderBy(dt => dt);

if (fileDates.Any())
{
    DateTime firstDate = fileDates.First();  // 2011-11-17 23:05:17,266
    DateTime lastDate  = fileDates.Last();   // 2011-11-17 23:17:08,862
}
于 2012-06-05T07:25:44.237 回答
1

这是一个如何解析的示例:

//init datetime list for log entries
List<DateTime> logDates = new List<DateTime>();

//Define regex string
string pattern = @"(?<logDate>(\d){4}-(\d){2}-(\d){2}\s(\d){2}:(\d){2}:(\d){2})";
Regex reg = new Regex(pattern);

//read log content
string logContent = File.ReadAllText("test.log");

//run regex
MatchCollection matches = reg.Matches(logContent);


//iterate over matches
foreach (Match m in matches)
{
    DateTime logTime = DateTime.Parse(m.Groups["logDate"].Value);
    logDates.Add(logTime);
}

//show first and last entry
Console.WriteLine("First: " + logDates.First());
Console.WriteLine("Last: " + logDates.Last());

我已经删除了几毫秒的逗号,只是为了更容易解析。

问候弗洛里安

于 2012-06-05T06:50:42.607 回答