flayn
flayn

Reputation: 5322

Reading the Windows Event Log with C# (Source != ProviderName != SourceName)

I am using C# to read the Windows Event Log and I want to select/filter entries from it. The problem is that the information displayed in the Event Viewer is not always matching the data I get from c#.

for example:

EventViewer "Source": "User Profile Service"

Using the EventLogEntry class: Property "Source": "Microsoft-Windows-User Profiles Service"

Using the EventLogReader class: Property "ProviderName": "Microsoft-Windows-User Profiles Service"

Using WMI: "SourceName": "Microsoft-Windows-User Profiles Service"

I need to be able to read the exact information displayed in the EventViewer, where can I get this information from?


Reading the EventLog message...

When reading the EventLog message using the EventLogEntry class I occasionally get the following string:

The description for Event ID "xxx" in Source "xxx" cannot be found

Again, this does not match the message displayed in the EventViewer... I have tried using the EventLogReader.FormatDescription() method and it gives me the right (the same as the EventViewer) message, BUT for some entries it simply returns null, while the EventLogEntry.Message contains the proper text.

What is the correct way to retrieve the message of the event to get the same message as the one displayed in the EventViewer?

Upvotes: 3

Views: 16810

Answers (2)

wildriver
wildriver

Reputation: 21

It appears that the "Source" string shown in the "Source" column in the Event Viewer is abbreviated. Also it seems that when you try to create an EventLog in C# only the logtype matters e.g. "Application", "System" etc. Once you create an EventLog it will contain all the entries for that logtype regardless of what you specified a source.

In order to get an event based on "Source" you want to iterate over the entries and filter only the entries for that "Source". Just keep in mind that the actual source name is not the same as what you see in the Event Viewer. For example for Source "Winlogon" the actual source name would be: "Microsoft-Windows-Winlogon" and so on.

Upvotes: 2

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

var eventLog = new EventLog("logName", "machine", "source");
foreach(var entry in eventLog.Entries)
{
}

That is a fairly basic swag at interacting with the log. If you need deeper filtering that source, you can write a LINQ query on the Entries. As shown here.

As for the error, one common reason is not having the proper access to the events and/or registry on the box in question. Since you can see data in question in EventViewer, I am suspecting a permissions error is a good possibility.

Upvotes: 2

Related Questions