从最新到最旧读取事件日志

lei*_*d13 4 .net c# windows event-log

我编写了一个简短的程序,使用启动和关闭时发布的事件日志消息来确定远程 PC 的正常运行时间。目前的逻辑是:

  foreach (eventlogentry)
  {
       if (entryTime > OldestTime)
       {
            if (entry = Startup)
            {
                 addOnTime(entry.Time);
            }
            if (entry = Shutdown)
            {
                 addOffTime(entry.Time);
            }
       }
  }
Run Code Online (Sandbox Code Playgroud)

“OldestTime”定义向后扫描多远的时间......

我想知道是否有任何方法可以轻松修改我的程序以从最新到最旧读取事件?

它正在读取远程事件日志,并且运行此函数需要一段时间,因为它从最后开始并向前读取。

我知道这一点是因为我在第一个“if”块中添加了一个“else”块以跳出 foreach 块,如果条目不在我们正在寻找的时间跨度内并且程序在它读取的第一个事件处停止。

Jur*_*ers 5

你问这个问题已经有一段时间了,但我遇到了同样的问题并找到了解决方案。

using System.Diagnostics;
using System.Linq;

EventLog events = new EventLog("Application", System.Environment.MachineName);
foreach (EventLogEntry entry in  events.Entries.Cast<EventLogEntry>().Reverse())
{
    //Do your tasks
}
Run Code Online (Sandbox Code Playgroud)

这个 awnser 仍然没有向前枚举它那么快,但它比使用循环将项目复制到列表要优雅一些。

@ leinad13,对于您的应用程序,您需要将 System.Environment.MachineName 更改为包含您想要事件的计算机名称的字符串,并将“应用程序”更改为您想要查看的日志。我认为你的情况是“系统”。

  • EventLogEntryCollection 支持索引。最好用一个反向整数迭代器循环它,即`for (int i=collection.Count;i &gt; 0;i--) { collection[i].whatever}` (3认同)