You can use the system. serviceprocess. servicecontroller class to control Windows Services.
The Cui project must be referenced by system. serviceprocess.
Note that the service name and display name are different. We use the service name when calling. Right-click the service name, and the details are displayed in the Properties window.
For automatic service update, "Automatic Updates" is the display name, and its service name is: wuauserv.
1. Obtain all services and their statuses
Servicecontroller [] SCS = servicecontroller. getservices ();
Foreach (servicecontroller SC in SCS)
{
Console. writeline ("{0} ({1}); Status: {2}", SC. displayname, SC. servicename, SC. status );
}
2. Check whether the service has been installed
Bool exists = false;
Servicecontroller [] SCS = servicecontroller. getservices ();
Foreach (servicecontroller SC in SCS)
{
If (string. Compare (SC. servicename, "MSSQLServer", true) = 0)
{
Exists = true;
Break;
}
}
3. Check service status
Servicecontroller SC = new servicecontroller ("MSSQLServer ");
If (SC. Status = servicecontrollerstatus. Stopped)
Console. writeline ("STOPPED ");
4. start or stop the service (canstop and other attributes may also be used)
Servicecontroller SC = new servicecontroller ("MSSQLServer ");
If (SC. Status = servicecontrollerstatus. Stopped)
{
SC. Start ();
SC. waitforstatus (servicecontrollerstatus. Running );
}
Else
{
SC. Stop ();
SC. waitforstatus (servicecontrollerstatus. Stopped