2

I'am trying to write some messages to Windows Event log.

The (security) exception will be thrown when calling function "SourceExists()".

private bool CheckIfEventLogSourceExits()
    {
        try
        {
            if (!EventLog.SourceExists(this.BaseEventLog))
            {
                return false;
            }
            return true;
        }
        catch (System.Security.SecurityException)
        {
            return false;
        }
    }

All answers to this question are explaining how you can MANUALLY resolve issue. Like here: Stackoverflow Thread. Solution would be changing some registry keys

But you can't expect that everyone who consumes your application is aware of these changes.

So my question is, how can we solve this issue programmatically?

Below my code:

 try
            {
                string sLog = "Application";
                if (CheckIfEventLogSourceExits())
                {
                    EventLog.CreateEventSource(this.BaseEventLog, sLog);
                }

                EventLog.WriteEntry(this.BaseEventLog, message, eventLogEntryType);
            }
            catch (Exception ex)
            {
                ex.Source = "WriteToEventLog";
                throw ex;
            }
Community
  • 1
  • 1
JVGAG
  • 107
  • 2
  • 12

1 Answers1

-2

I know it's too late for this posting, but the answer, I found from similar experience, is that the service you're running under doesn't have administrative rights to the machine and, thus, can't write to the logs.

It's easy enough to figure out if an app is being run under admin rights. You can add something like this to your code with a message box advising the user to run "admin".

private void GetServicePermissionLevel()
{
bool bAdmin = false;
try {
    SecurityIdentifier sidAdmin = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
    AppDomain myDomain = Thread.GetDomain();
    myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
    if (myPrincipal.IsInRole(sidAdmin)) {
        bAdmin = true;
    } else {
        bAdmin = false;
    }
} catch (Exception ex) {
    throw new Exception("Error in GetServicePermissionlevel(): " + ex.Message + " - " + ex.StackTrace);
} finally {
    _ServiceRunAsAdmin = bAdmin;
}
}
Brian
  • 3,653
  • 1
  • 22
  • 33