0

I am trying to do the following from this documentation to add to the event log when the service is started / stopped. When I install the service on my local machine and try to start it the code in the constructor errors out due to permissions:

public MyService()
{
    InitializeComponent();

    eventLog1 = new System.Diagnostics.EventLog();
    if (!System.Diagnostics.EventLog.SourceExists("MySource")) 
    {         
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource","MyNewLog");
    }
    eventLog1.Source = "MySource";
    eventLog1.Log = "MyNewLog";
}

protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("In OnStart");
}

protected override void OnStop()
{
    eventLog1.WriteEntry("In onStop.");
}

Here is the error that shows in the event viewer:

Application: MyService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Security.SecurityException
Stack:
   at System.Diagnostics.EventLog.FindSourceRegistration(System.String, System.String, Boolean, Boolean)
   at System.Diagnostics.EventLog.SourceExists(System.String, System.String, Boolean)
   at System.Diagnostics.EventLog.SourceExists(System.String)
   at PharmaLytics.Reforecaster.ReforecasterService..ctor()
   at PharmaLytics.Reforecaster.Program.Main()
William Venice
  • 329
  • 2
  • 7
  • 16
  • 1
    The dupe explanation is pretty good. The problem is only admins can create event log sources, and your service shouldn't be an admin. The only solution is to create the event log from another application running as admin. Typically this is done via an installer. If your application isn't installed, write a simple console app that creates the log source. If you want to get fancy, you could force elevation on execution of the console app via a manifest, or via http://stackoverflow.com/questions/133379/elevating-process-privilege-programatically –  Sep 18 '15 at 15:54
  • What if I create the Event Source and Log outside of the application. Will writing to it be a problem? – William Venice Sep 18 '15 at 16:10
  • Well, the linked question's answer suggests so, however I wouldn't be surprised if you don't have to change the ACL to allow the service's account access to the log. IIRC, that needs to be done on the registry key. But try it without tinkering and see what happens. –  Sep 18 '15 at 16:20

0 Answers0