Using C# and Linq to read a Windows EventLog file (.evtx)

The EventLogReader and EventLogQuery in the the System.Diagnostics.Eventing.Reader namespace are what constitutes the basis of reading an eventlog file, for instance one that your server people sent you from the production environment. As the Microsoft documentation shows, however, these classes and methods are pretty much geared towards XPath queries instead of “pure” Linq to objects.

I prefer the latter so I’ll propose a simple method that will make this possible:

static IEnumerable<EventLogRecord> LogRecordCollection(string filename, string xpathquery = "*")
     var eventLogQuery = new EventLogQuery(filename, PathType.FilePath, xpathquery);

     using (var eventLogReader = new EventLogReader(eventLogQuery))
         EventLogRecord eventLogRecord;

         while ((eventLogRecord = (EventLogRecord)eventLogReader.ReadEvent()) != null)
             yield return eventLogRecord;

Note that you can so to speak preselect with an XPath query, but I guess that most times performance is not really an issue here – my usecase is just a batch program that can produce a simple statistic.

A way of using the LogRecordCollection could be like this:

var t = from l in LogRecordCollection("e:\\evt.evtx")
                    where l.ProviderName.StartsWith("SQL") && l.TimeCreated > new DateTime(2011, 03, 01) 
                    select l;


In case a preset XPath query is needed it could be like "Event/System/Provider[@Name=’SQLVDI’]", but do look into some XPath samples for more interesting uses.

Getting the log-message is a bit more troublesome, as this is sometimes a collection of strings, but what I need here is just getting the first one like so: var s = eventLogRecord.Properties.Count > 0 ? eventLogRecord.Properties[0].Value.ToString() : “";

There is of course also the possibility of using the Microsoft LogParser 2.2 commandline tool to select and reformat a log-file, but to me C# is both a better and faster option.


One thought on “Using C# and Linq to read a Windows EventLog file (.evtx)

  1. Vish

    Hi, Very nice article.. However, I wanted to query a .evtx files based on record id of the event.
    Could I change the xpathquery from “*” to “RecordId=” and return the message text of that event..?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s