nlstack01
nlstack01

Reputation: 839

Issue Reading System Event Errors C#

The code below works ok on a Win7 machine, but when I run it on Win10 it only displays the first 3 errors and stops

    string machine = ".";
    var aLog = new EventLog("system", machine);

    List <EventLogEntry> entries = (from entry in aLog.Entries.Cast<EventLogEntry>()
                                   where entry.TimeWritten >= DateTime.Today &&
                                         entry.EntryType == EventLogEntryType.Error
                                   orderby entry.TimeWritten descending
                                   select entry).ToList();

    Console.WriteLine("COUNT= " +entries.Count); //This is 3 but there is 10 system errors
    foreach(var entry in entries)
    {
        Console.WriteLine(entry.Source);
        Console.WriteLine(entry.Message);
        Console.WriteLine();
    }

EventViewer

Upvotes: 1

Views: 35

Answers (1)

Igor
Igor

Reputation: 62238

The code is doing exactly what you are asking of it, retrieving everything that has a date greater than or starting on the beginning of today. Your filtered view in the screen shot is everything that happened in the last 24 hours, that is not the same.

If you wanted to use that view then change your where clause.

var twentyFourHoursAgo = DateTime.Now.AddHours(-24); // not sure if this should be UTC or local, change to UtcNow if applicable

List <EventLogEntry> entries = (from entry in aLog.Entries.Cast<EventLogEntry>()
       where entry.TimeWritten >= twentyFourHoursAgo &&
             entry.EntryType == EventLogEntryType.Error
       orderby entry.TimeWritten descending
       select entry).ToList();

Upvotes: 1

Related Questions