我正在使用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
Run Code Online (Sandbox Code Playgroud)
现在我想读取此文件,并希望第一次记录日志和最后日期
如何在此文本文件中获取第一次日期和上次更新日期?
现在我正在使用以下代码阅读此文本文件:
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));
}
Run Code Online (Sandbox Code Playgroud)
我编写的这段代码用于获取第一次日期和最后更新日期,如果Exception行是单行的,但它不适用于具有多行的异常,如上所示.现在这是我的问题.任何人都可以告诉我如何获取此文本文件中的第一个和最后一个日期?
这是一种使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5294 次 |
| 最近记录: |