Search code examples
c#visual-studio-2017windows-services

Windows service programmed in C# can be installed and started, but doesn't "do" what it should?


So basically I'm trying to program a Windows Service in C# under Visual Studio 2017. As the service didn't do what i wanted to do i made a test service with a very rudimentary logic to test if it even does what i want in the OnStart() Method. The reason why i chose to manually write a string into the event log is because i want to make sure that there is no writing permission issue. I mean if the service is installed and started, it should write the line into the log shouldn't it?

So:

namespace WindowsService3
{
    public class Program : System.ServiceProcess.ServiceBase
    {


        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }

        protected override void OnStart(string[] args)
        {
            this.EventLog.WriteEntry("Hello");
        }

        protected override void OnStop()
        {

        }
    }
}

I added a ProjectInstaller, added the service name to it as well as specifying it for LocalSystem. Then i used the following line to install it:

C:\Windows\system32>sc \\10.10.0.122 create TESTService binPath= "C:\temp\service\WindowsService1.exe"

The service can now be seen in the service manager and even started. Without problems... In the eventlog though i don't see the specified line. So it seems the service is correctly started, but it doesn't user the logic in the OnStart() method. I have no idea why. I also tried things like creating a text file via the OnStart() method at first... Also no success. What am i doing wrong? Again, the service IS installed and IS started as the Event log and the service manager suggest.

Edit: My problem is that no code is executed in OnStart at all. I can't write a file, i can't write a log, nothing. The service is just installed and can be started, but i doesn't do anything that is put into OnStart() and i don't know why. My coworkers can't figure it out either.

Edit2: The VS2017 template tells me to make the Program class static. But then I can't use OnStart() in it. But maybe this is my missunderstanding? In my example i made the Program class just public to implement OnStart() but maybe that was the mistake?


Solution

  • You have written your service code in the class Program, but your service that is started is named Service1, probably defined by the template in another file.

    Either edit Service1.cs to include your startup code, or edit your Program.cs to start your class:

    ServicesToRun = new ServiceBase[]
            {
                new Program() // <----
            };
    

    Putting your service and Program.cs in the same class is uncommon, it's indeed a good approach to keep them separate and have a separate Service class.