Instead you need to understand a little more about the EventLog object. The entire contents of an EventLog are read in when the EventLog is constructed (if the variant with a logname is used) or when the Log property is set for the object. The results of reading the event log are stored in the Entries property. The entries property is a collection of EventLogEntry objects. If you would like to see the contents of a particular EventLogEntry, you need "massage" the object a little more by accessing specific properties of the EventLogEntry class.
It is important to note that the Entries property is a read only property. You can't change the contents of the event log by modifying the Entries property. In order to change the event log, you need to use the "Write" methods.
The example below shows how to access the 10 most recent log entries from the System event log.
System Event Log Read Example
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ReadEventLogExample
{
class Program
{
static void Main(string[] args)
{
// There are three default event logs, Application, System and Security
EventLog systemLog = new EventLog("System");
// The entries member contains all the entries in the event log
// There is no need to perform a specific read operation on the event log
// The Entries member is read only, so you will need to use the write
// methods if you want to write to the EventLog
int entryCount = systemLog.Entries.Count;
entryCount = entryCount - 1; //We are using the count for a zero based index...
Console.WriteLine("The last 10 entries in the System event log");
for (int i = 0; i < 10; i++)
{
if (entryCount - i >= 0) //We only want positive indexes...
{
Console.WriteLine("------------------------------------\n");
Console.WriteLine("Time Generated: " + systemLog.Entries[entryCount - i].TimeGenerated);
Console.WriteLine("Time Written: " + systemLog.Entries[entryCount - i].TimeWritten);
Console.WriteLine("Source: " + systemLog.Entries[entryCount - i].Source);
Console.WriteLine("Entry Type: " + systemLog.Entries[entryCount - i].EntryType);
Console.WriteLine("Message: " + systemLog.Entries[entryCount - i].Message + "\n");
}
}
}
}
}
Additional Resources
EventLog Class (Microsoft)
EventLogEntry Class (Microsoft)
No comments:
Post a Comment