C# - Stop Windows Service

This code snippet shows how to stop a Windows Service using the service name. You will need to administer privileges to stop a service.

Program.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceProcess;  
  6.  
  7. namespace ConsoleApplication1  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             try  
  14.             {  
  15.                 string serviceName = "Service Name";  
  16.                 ServiceController sController = new ServiceController(serviceName);  
  17.                 sController.Stop();  
  18.  
  19.                 Console.WriteLine("Service stopped");  
  20.             }  
  21.             catch (Exception e)  
  22.             {  
  23.                 Console.WriteLine(e.Message);  
  24.             }  
  25.             Console.ReadKey();  
  26.         }  
  27.     }  
  28. } 

No comments:

Post a Comment