Hi,
I am using a dedicated account (with SDDL policy) to write event log entries to a custom event log. For this I use WindowsImpersonationContext and obtain a token with LogonUser:
WindowsIdentity impersonationIdentity = new WindowsIdentity(ptr);
WindowsImpersonationContext impersonationContext = impersonationIdentity.Impersonate();
EventLog.WriteEntry("MyCustomSource", DateTime.Now.ToLongTimeString(), EventLogEntryType.Warning);
impersonationContext.Undo();
NativeMethods.CloseHandle(ptr);
This piece of code produces event log entries, yet I also get a Win32Exception:
Unhandled Exception: System.InvalidOperationException: Cannot open log for source 'MyCustomSource'. You may not have write access. ---> System.ComponentModel.Win32Exception: Access is denied
Now, the exception disappears if I place a Thread.Sleep(500) after the impersonation line:
WindowsImpersonationContext impersonationContext = impersonationIdentity.Impersonate();
System.Threading.Thread.Sleep(500);
What is causing this exception and how come the event log entries get written even with the access denied exception?
Edit: And ofc I've registered the event source with the associated log before using it. I only included small code snippets to keep the message short.