事件日志自当前时间

时间:2014-10-03 12:52:45

标签: c# events

我对 C#事件日志有一点疑问。我需要编写一个简单的控制台应用程序,它将读取我将要设置的当前事件类型(应用程序,系统,安全性)。我有这个来源,它正在读取事件日志。

EventLog appLogs = new EventLog();
appLogs.Log = "Application";
foreach (EventLogEntry entry in appLogs.Entries)
{
    Console.WriteLine("\tEntry: " + entry.Message);
} 

这将给我当前的活动。我需要从我给予的时间开始的活动。

先谢谢你:)

2 个答案:

答案 0 :(得分:1)

使用entry.TimeWritten属性过滤要打印的属性。

可以使用简单的ifLinq查询来完成此操作。

        EventLog appLogs = new EventLog();
        appLogs.Log = "Application";
        DateTime timeToWrite = DateTime.Now;

        foreach (EventLogEntry entry in appLogs.Entries)
        {
            if (entry.TimeWritten == timeToWrite)
                Console.WriteLine("\tEntry: " + entry.Message);
        }

LINQ的

        EventLog appLogs = new EventLog();
        appLogs.Log = "Application";
        DateTime timeToWrite = DateTime.Now;

        var entriesToWrite = appLogs.Entries.Cast<EventLogEntry>().Where(x => x.TimeWritten == timeToWrite);

        foreach (EventLogEntry entry in entriesToWrite)
        {
            if (entry.TimeWritten == timeToWrite)
                Console.WriteLine("\tEntry: " + entry.Message);
        }

答案 1 :(得分:1)

您可以使用Linq查询条目:

DateTime searchDate = ...
var entries = appLogs.Entries.Cast<EventLogEntry>().Where(x => x.TimeWritten == searchDate);

foreach(var entry in entries)
{
    ...
}

由于EventLogEntryCollectionIEnumerable,而非IEnumerable<EventLogEntry>