1. Reference System. serviceprocess. dll
2. reference the system. serviceprocess namespace
UsingSystem. serviceprocess;
3. Declare the servicecontroller variable
PrivateServicecontroller _ controller;
4. Assume that the service name isServicesname,WriteCodeAs follows:
A: Start service.
1 Private Void Startservice ()
2 {
3 This . _ Controller = New Servicecontroller ( " Servicesname " );
4 Try
5 {
6 If (_ Controller. Status. Equals (servicecontrollerstatus. Stopped )) |
7 (_ Controller. Status. Equals (servicecontrollerstatus. stoppending )))
8 {
9 _ Controller. Start ();
10 }
11 Else
12 {
13 _ Controller. Stop ();
14 }
15 }
16 Finally
17 {
18 This . _ Controller. Refresh ();
19 This . _ Controller. Close ();
20 }
21 }
B: stop the service.
1 Private Void Stopservice ()
2 {
3 This . _ Controller = New Servicecontroller ( " Servicesname " );
4 Try
5 {
6 This . _ Controller. Stop ();
7 This . _ Controller. waitforstatus (servicecontrollerstatus. Stopped );
8 }
9 Finally
10 {
11 This . _ Controller. Refresh ();
12 This . _ Controller. Close ();
13 }
14 }
C: restart the service.
1 Private Void Resetservice ()
2 {
3 This . _ Controller = New Servicecontroller ( " Servicesname " );
4 Try
5 {
6 This . _ Controller. Stop ();
7 This . _ Controller. waitforstatus (servicecontrollerstatus. Stopped );
8 This . _ Controller. Start ();
9 This . _ Controller. waitforstatus (servicecontrollerstatus. Running );
10 }
11 Finally
12 {
13 This . _ Controller. Refresh ();
14 This . _ Controller. Close ();
15 }
16 }
D: If it is stopped, start the reverse operation and stop it.
1 Private Void Sstopservice ()
2 {
3 This . _ Controller = New Servicecontroller ( " Servicesname " );
4 Try
5 {
6 This . _ Controller. Stop ();
7 This . _ Controller. waitforstatus (servicecontrollerstatus. Stopped );
8 This . _ Controller. Start ();
9 This . _ Controller. waitforstatus (servicecontrollerstatus. Running );
10 }
11 Finally
12 {
13 This . _ Controller. Refresh ();
14 This . _ Controller. Close ();
15 }
16
17 }