title: Stop/Start service in code in Windows 7
body: <p>I am trying to write a app and service which monitor a given set of services and a) makes sure they are running and b) based on certain criteria, restart them as needed.</p>
  
  <p>I keep running into an access denied error.</p>
  
  <p>If I simply iterate through the processes on the system, find the one I want like so:</p>
  
  <pre><code>foreach (ServiceController sc in ServiceController.GetServices())
     {                
         if(sc.ServiceName == "MyServiceName")
         {
              sc.Stop();
              sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 60));
              sc.Start(); 
         }            
     }   
  </code></pre>
  
  <p>I get:</p>
  
  <pre><code>InnerException: System.InvalidOperationException
          Message="Cannot open My Service service on computer '.'."
          Source="System.ServiceProcess"
          StackTrace:
               at System.ServiceProcess.ServiceController.GetServiceHandle(Int32 desiredAccess)
               at System.ServiceProcess.ServiceController.Stop()
               at lib.ListServices() in D:\lib.cs:line 552
               at lib.Init() in D:\lib.cs:line 56
     InnerException: System.ComponentModel.Win32Exception
               Message="Access is denied"
               ErrorCode=-2147467259
               NativeErrorCode=5
               InnerException: 
  </code></pre>
  
  <p>I have tried to impersonate a user, I have tried to do the same code from another service which is running as a system service.  Neither of which have actually been able to affect the service.  If its started, I cannot stop it.  If its stopped, I cannot start it.  I know this is all related to permissions I'm just not finding a mechanism that actually lets me control the service.</p>
  
  <p>Any assistance would be greatly appreciated.</p>