Start/Stop Remote Windows Service From Client Application

This example shows how to start/stop remote Windows Service from client machine using C# application.

First, create a Windows application and put 4 label controls for displaying service name and status of the service.

On the button click event, we need to write the following lines of code.

 

  1. private void btnStartStop_Click(object sender, EventArgs e) {  
  2.     try {  
  3.         string serviceName = "ServiceName";  
  4.         string IP = "xxx.xxx.x.xx"// remote IP  
  5.         string username = "username"// remote username  
  6.         string password = "password"// remote password  
  7.         ConnectionOptions connectoptions = new ConnectionOptions();  
  8.         connectoptions.Username = username;  
  9.         connectoptions.Password = password;  
  10.         ManagementScope scope = new ManagementScope("\\\\xxx.xxx.x.xx\\root\\Machine Name");  
  11.         scope.Options = connectoptions;  
  12.         //WMI query to be executed on the remote machine  
  13.         SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");  
  14.         using(ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) {  
  15.             ManagementObjectCollection collection = searcher.Get();  
  16.             foreach(ManagementObject service in collection.OfType < ManagementObject > ()) {  
  17.                 if (service["started"].Equals(true)) {  
  18.                     //Start the service  
  19.                     service.InvokeMethod("StopService"null);  
  20.                     btnStartStop.Text = "Start";  
  21.                     lblServiceName.Text = serviceName;  
  22.                     lblServiceStatus.Text = "Stopped";  
  23.                 } else {  
  24.                     //Stop the service  
  25.                     service.InvokeMethod("StartService"null);  
  26.                     btnStartStop.Text = "Stop";  
  27.                     lblServiceName.Text = serviceName;  
  28.                     lblServiceStatus.Text = "Running";  
  29.                 }  
  30.             }  
  31.         }  
  32.     } catch (NullReferenceException) {  
  33.         throw;  
  34.     }  
  35. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  36. if ('this_is' == /an_example/) {  
  37.     of_beautifier();  
  38. else {  
  39.     var a = b ? (c % d) : e[f];  
  40. }  
Ebook Download
View all
Learn
View all