开发者

Read Event Log From Newest to Oldest

I have written a short program to establish the uptime for remote PC's using the event log messages which are posted at startup and shutdown. Currently the logic is :

  foreach (eventlogentry)
  {
       if (entryTime > OldestTime)
       {
            if (entry = Startup)
            {
                 addOnTime(entry.Time);
            }
            if (entry = Shutdown)
            {
                 addOffTime(entry.Time);
            }
       }
  }

"OldestTime" define how far to scan backwards in time....

开发者_如何转开发

I would like to know if there is anyway to easily ammend my program to read the events from newest to oldest?

It's reading remote event logs and its taking a while for this function to run, as it starts at the end and reads forward.

I know this because I added a "else" block to the first "if" to break out of the foreach block, if the entry isnt within the timespan we are looking for and the program stop's at the first event it reads.


It has been a while since you asked this question, but i ran into the same problem and found a solution.

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
}

This awnser still is not as fast as to just enumerate it forward but it is a bit more elegant than using a loop to copy items to a list.

@leinad13, for your application you need to change System.Environment.MachineName to a string with the name of the computer you want the events from and change "Application" to the log you want to see. I think "System" in your case.


Your best solution may be to move the data into a list and then reverse the order of that. Something like the following:

EventLog eventLog = new EventLog();
eventLog.Log = myEventLog;
var eventList = new List<EventLogEntry>();

foreach(EventLogEntry entry in eventLog.Entries)
{
      eventList.Add(entry);
}

eventList.Reverse();

That should get the data in the reverse order, i.e. latest first, and then you can just process it as before but this time exit the loop when you hit a date before the oldest time.

Its not an ideal solution as you are still processing the whole log but it may be worth trying out to see if you get an improvement in performance

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜