Ayush
Ayush

Reputation: 42450

Start and stop a service

I am using the following code fragment to change the account and password credentials of a Windows Service. However, this only works if the service is stopped.

How can I, programatically, stop the service before making these changes, and then start it again?

namespace ServiceAccount
{
    class Program
    {
        static void Main(string[] args)
        {
            string serviceName = "DummyService";
            string username = ".\\Service_Test";
            string password = "Password1";

            string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
            using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
            {
                object[] wmiParams = new object[11];
                wmiParams[6] = username;
                wmiParams[7] = password;
                service.InvokeMethod("Change", wmiParams);
            }

        }
    }
}

Upvotes: 2

Views: 356

Answers (2)

Oded
Oded

Reputation: 499392

Use the ServiceController class. It exposes methods to start and stop a service, provided you know its name.

ServiceController sc = new ServiceController("Simple Service");
if (sc.Status == ServiceControllerStatus.Stopped)
{
  sc.Start();
}

Upvotes: 6

openshac
openshac

Reputation: 5165

There's an article here showing you how: http://www.csharp-examples.net/restart-windows-service/

Upvotes: 2

Related Questions