Start Windows Service programmatically

C#Windows Services

C# Problem Overview


I am having an issue with an application that I am creating. I am trying to start a windows service through my C# app. When I click my start button, it looks like everything goes through but when I log into the server, the service still does not show that it is running. However, the second time I run it, I get an exception that says the instance of the service is already running. Again when I log into the server, the service appears to be stopped. Has anyone ever seen this?

Here is my code.

try
{
    while (reader.Read())
    {
        int timeoutMilliseconds = 1000;
        string serviceName = reader["ServiceName"].ToString();
        string permission = reader["Permission"].ToString();

        if (permission == "E")
        {
            lblServStartSuccess.Visible = true;

            ServiceController service = new ServiceController(serviceName);
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
        else
        {
            lblServErrorStart.Visible = true;
        }
    }
}
catch (Exception ex)
{
    Response.Write(ex.ToString());
}

EDIT: Here is the exception I received on one service:

> System.InvalidOperationException: Service Logical Disk Manager > Administrative Service was not found on computer '.'. ---> > System.ComponentModel.Win32Exception: The specified service does not > exist as an installed service --- End of inner exception stack trace

I know the service exists. Do I need to add something in front of the service to tell it what server to look at?

C# Solutions


Solution 1 - C#

If the code you showed is executing on a different machine than where the service is supposed to run (I'm not clear from your comments if that's the case or not), you would need to provide the machine name in the ServiceController constructer.

Is it possible you are successfully starting the service, but not on the machine you think? That would fit the symptoms you describe.

ServiceController service = new ServiceController(serviceName, serverName);

Also see ServiceController constructor documentation.

Solution 2 - C#

Here is code I have in a Window Service responsible for stopping starting other services running on the same server.

ServiceController controller = new ServiceController(serviceName);
if (controller.Status==ServiceControllerStatus.Running)
    controller.Stop();

if (controller.Status==ServiceControllerStatus.Stopped)
    controller.Start(); 

Solution 3 - C#

This is an old thread, but google got me here. My services, even after successfully starting, would still query back as stopped. If you add

service.Refresh();

It will query the actual current status instead of the stored state from a previous query. I don't know why it works like this, but it does.

P.S.: I added a minute long time out and still got a service is stopped response without the refresh.

Solution 4 - C#

public static void StartService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);
        try
        {
            int millisec1 = 0;
            TimeSpan timeout;

            // count the rest of the timeout
            int millisec2 = Environment.TickCount;
            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec1));
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);

        }
        catch (Exception e)
        {
            Trace.WriteLine(e.Message);
        }
    }
    public static void StopService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);
        try
        {
            int millisec1 = 0;
            TimeSpan timeout;
            if (service.Status == ServiceControllerStatus.Running)
            {
                millisec1 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }


        }
        catch (Exception e)
        {
            Trace.WriteLine(e.Message);
        }
    }
    public static void RestartService(string serviceName, int timeoutMilliseconds)
    {
        ServiceController service = new ServiceController(serviceName);
        try
        {
            int millisec1 = 0;
            TimeSpan timeout;
            if (service.Status == ServiceControllerStatus.Running)
            {
                millisec1 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            }
            // count the rest of the timeout
            int millisec2 = Environment.TickCount;
            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);

        }
        catch (Exception e)
        {
            Trace.WriteLine(e.Message);
        }
    }

Dont forget to add ServiceProcess as referance using System.ServiceProcess;

Solution 5 - C#

First of all you need to add reference of the DLL (ServiceProcess) in your project References as like:

Right click on References in Solution Explorer -> Add Reference -> Assemblies -> 
Framework -> System.ServiceProcess

Then add ServiceProcess DLL in your project:

using System.ServiceProcess;

After that use this code:

ServiceController service = new ServiceController(yourServiceName);

Solution 6 - C#

Just try service.Start(); without the timeout or waitforstatus and hook its events to see whats happening.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - C#hatchet - done with SOverflowView Answer on Stackoverflow
Solution 2 - C#Gary KindelView Answer on Stackoverflow
Solution 3 - C#MattyMattView Answer on Stackoverflow
Solution 4 - C#Nikhil DineshView Answer on Stackoverflow
Solution 5 - C#stefanView Answer on Stackoverflow
Solution 6 - C#tcablesView Answer on Stackoverflow