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);
}
}
}
}
Use the
ServiceControllerclass. It exposes methods to start and stop a service, provided you know its name.