Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save forcewake/f2876067f1f0c833fc45 to your computer and use it in GitHub Desktop.
Save forcewake/f2876067f1f0c833fc45 to your computer and use it in GitHub Desktop.
// 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