Skip to content

Instantly share code, notes, and snippets.

@colinbowern
Created June 20, 2013 13:16
Show Gist options
  • Save colinbowern/5822569 to your computer and use it in GitHub Desktop.
Save colinbowern/5822569 to your computer and use it in GitHub Desktop.
The call to EventLog.CreateEventSource causes a SecurityException because it has to cycle through the Security log to check. Alternatively you can go into the registry and setup the log and source yourself. Note that this either requires the process to be elevated (see http://stackoverflow.com/a/2818776/79842) or that your user has delegated mod…
// Need to go direct to the registry as the EventLog.CreateEventSource
// method cycles through all logs, including the Security log, to
// verify that the source does not exist and is unique
try
{
var logKeyName = String.Format(CultureInfo.InvariantCulture, @"SYSTEM\CurrentControlSet\Services\EventLog\{0}", log);
var sourceKeyName = String.Format(CultureInfo.InvariantCulture, @"SYSTEM\CurrentControlSet\Services\EventLog\{0}\{1}", log, source);
using (Registry.LocalMachine.OpenSubKey(logKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree) ??
Registry.LocalMachine.CreateSubKey(logKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree))
using (var sourceKey = Registry.LocalMachine.OpenSubKey(sourceKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree) ??
Registry.LocalMachine.CreateSubKey(sourceKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree))
{
Debug.Assert(sourceKey != null, "sourceKey should exist by this point");
var eventMessageFile = sourceKey.GetValue("EventMessageFile");
if (eventMessageFile == null)
{
var messageFile = Path.Combine(
RuntimeEnvironment.GetRuntimeDirectory(), "EventLogMessages.dll");
sourceKey.SetValue("EventMessageFile", messageFile, RegistryValueKind.String);
}
}
}
catch (UnauthorizedAccessException exception)
{
throw new SecurityException(@"This process needs to be run in elevated mode or you need to delegate modify access to HKLM\SYSTEM\CurrentControlSet\Services\EventLog to the current user.", exception);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment