C# – SecurityException when writing to the Windows Event Log

Problem

When your application tries to write to the Windows Event Log, you get the following exception:

System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique.

This exception is referring to the event log source. When you write to the Windows Event Log, you have to specify the event log source to use. If the source doesn’t exist, it’ll try to create it for you in the registry. By default, this requires administrator permissions. If your application doesn’t have the right permissions, you’ll get the SecurityException.

Note: You’ll also run into this exception when trying to use EventLog.SourceExists() / EventLog.CreateEventSource() if your app doesn’t have the right permissions.

Solution

The simplest solution is to run as admin at least once to get the event log source registered.

How exactly you solve it will depend on your specific scenario (environment, type of users, etc…). Here are a few options below.

Option 1 – Run as admin when installing / deploying

This is really only a problem when initially registering the event log source. So ideally, you’d take care of this during installation / deployment.

Run the installer / deployment as administrator so it can register the event log source.

Option 2 – Register the event log source with a separate console app / PowerShell

Run PowerShell as admin and execute the following to register the event log source:

[System.Diagnostics.EventLog]::WriteEntry("MySource", "initializing event log source")
Code language: PowerShell (powershell)

Or create a console app and run it as admin (or run your Windows Service in console app mode):

using System.Diagnostics;

if (!EventLog.SourceExists("MySource"))
{
	EventLog.CreateEventSource(source: "MySource", logName: "Application");
}

Code language: C# (cs)

Note: Use EventLog.SourceExists() + EventLog.CreateEventSource() if you want to avoid writing dummy message just to initialize the event log source.

2 thoughts on “C# – SecurityException when writing to the Windows Event Log”

Leave a Comment