Problem when trying to use EventLog.SourceExists method in .NET

后端 未结 4 1961
旧时难觅i
旧时难觅i 2021-01-03 21:31

I am trying to use eventlogs in my application using C#, so I added the following code

if (!EventLog.SourceExists(\"SomeName\"))
EventLog.CreateEventSource(\         


        
4条回答
  •  离开以前
    2021-01-03 22:14

    Yes, it's a permissions issue, but it's actually worse than indicated by the currently accepted answer. There are actually 2 parts.

    Part 1

    In order to use SourceExists(), the account that your code is running under must have "Read" permission for the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog key and it must also have "Read" permissions on each of the descendant-keys. The problem is that some of the children of that key don't inherit permissions, and only allow a subset of accounts to read them. E.g. some that I know about:

    • Security
    • State
    • Virtual Server

    So you have to also manually change those when they exist.

    FYI, for those keys (e.g. "State") where even the Administrator account doesn't have "Full Access" permission, you'll have to use PsExec/PsExec64 to "fix" things. As indicated in this StackOverflow answer, download PsTools. Run this from an elevated command prompt: PsExec64 -i -s regedit.exe and you'll them be able to add the permissions you need to that key.

    Part 2

    In order to successfully use CreateEventSource(), the account that your code is running under must have "Full Control" permissions on HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog as well as have "Full Control" permissions on the log you're adding the new source to.

    But wait, there's more...

    It is also important to know that both CreateEventSource() and WriteEntry() call SourceExists() "under the hood". So ultimately, if you want to use the EventLog class in .Net, you have to change permissions in the registry. The account needs "Full Control" on the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog key and "Read" for all children.

    Commentary: And I believe all of this mess is because when Microsoft originally designed the EventLog, they decided it was critical that people would be able to log something by "Source" without needing to know what log that "Source" went with.

提交回复
热议问题