写入Event Log触发Security exception未被用户代码处理问题求助
That security exception is almost always a permissions issue when dealing with the Windows Event Log—here's how to resolve it:
1. Pre-Create Your Event Source (Requires Admin Rights Once)
The most common cause is that your application is trying to create a new event source (MyEventSource) on the fly, which requires administrative privileges. To fix this:
- Run your application once as an administrator to create the source upfront.
- Modify your code to check if the source exists before using it (this prevents repeated attempts to create it):
try { // Check if the event source exists first if (!EventLog.SourceExists("MyEventSource")) { // This line requires admin rights to run successfully EventLog.CreateEventSource("MyEventSource", "Application"); } db.Entry(object).State = EntityState.Modified; db.SaveChanges(); } catch (Exception ex) { EventLog.WriteEntry("MyEventSource", ex.StackTrace, EventLogEntryType.Warning); }
Once the source is created, your app can write to it without admin rights (assuming the user account has write permissions to the log).
2. Grant Write Permissions to Your User Account
If you still get the exception after creating the source, your app's user account might not have permission to write to the Event Log. To fix this:
- Open Event Viewer (search for it in Windows Start Menu).
- Navigate to Windows Logs > Application, right-click it, and select Properties.
- Go to the Security tab, click Edit, then Add your application's user account.
- Grant the account Write permissions, then click OK to save changes.
3. Alternative: Use an Existing Event Source
If creating a custom source is too cumbersome, you can use an existing source like the default "Application" source (though this will mix your events with other system/application events):
catch (Exception ex) { EventLog.WriteEntry("Application", ex.StackTrace, EventLogEntryType.Warning); }
内容的提问来源于stack exchange,提问作者makeeasier

