martijn_himself
martijn_himself

Reputation: 1570

Serializing a .NET EventLogEntry instance to XML

When using the Event Viewer in Windows 7, there is a separate 'XML View' of an event that can be accessed from the Event Properties dialog. This XML refers to the http://schemas.microsoft.com/win/2004/08/events/event namespace.

When I subscribe to Windows Events using the .NET framework classes in the System.Diagnosticsnamespace and retrieve event objects in the form of EventLogEntry instances, is there a way to serialize these instances to the XML format mentioned above? I can not seem to find any.

Thank you very much for your response.

Update: thanks to jmservera I have found out there is a different and better API in the System.Diagnostics.Eventing.Reader namespace, however this API does not support deployment to Windows Server 2003/ XP.

Update 2: I have accepted jmservera's answer, because it has lead me to the solution. If you are targetting Vista/ Windows Server 2008 follow jmservera's suggestion and use the API in the newer namespace. If, however, you need to support previous OS's you will have to use the older API and serialize the EventLogEntry to XML yourself.

Upvotes: 2

Views: 2683

Answers (1)

jmservera
jmservera

Reputation: 6682

You have to use the System.Diagnostics.Eventing.Reader namespace like this:

static void Main(string[] args)
{
 EventLogQuery query = new EventLogQuery("System", PathType.LogName);
 EventLogWatcher watcher = new EventLogWatcher(query);
 watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(watcher_EventRecordWritten);
 watcher.Enabled = true;
 Console.ReadLine();
}

static void watcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
 Console.WriteLine(e.EventRecord.ToXml());
}

Upvotes: 4

Related Questions