Service controller


We can control the services of local and remote system using the following code.

Following is the sample code for start , stop and show all the services. This will use to control the remote server also.


Namespace part


using System;
using System.ServiceProcess;


Start the service

public static void StartMyService(string Myserver, string Myservice) {
Console.WriteLine("Starting Service");
ServiceController MyServiceController;

if (Myserver.Length != 0)
MyServiceController = new ServiceController(Myserver, service);
else
MyServiceController = new ServiceController(Myservice);

MyServiceController.Start();
}



Stop the service

public static void StopMyService(string Myserver, string Myservice) {
Console.WriteLine("Stopping the service");
ServiceController MyServiceController;

if (Myserver.Length != 0)
MyServiceController = new ServiceController(server, Myservice);
else
MyServiceController = new ServiceController(Myservice);

MyServiceController.Stop();
}



Show All the services


public static void ShowMyServices(string Myserver) {
ServiceController[] Myservices;
if (Myserver.Length != 0)
Myservices = ServiceController.GetServices(Myserver);
else
Myservices = ServiceController.GetServices();

foreach (ServiceController svc in Myservices) {
Console.WriteLine(svc.DisplayName);
}
}




The class ServiceController is used to achive our target.

Thanks
Nathan


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: