title: ServiceController API will not recognise that a service has stopped
body: <p>I'm working on an installer that copies files into Program Files and then runs a service (via one of the files that was copied over). On the first installation this will work with no problems, but issues start to occur when the installer is run and the service is already running on the machine. This is because the installer is attempting to replace the files that already exist in Program Files, but one of those files is in use by the Windows service, so it cannot be replaced unless the service is stopped.</p>
  
  <p>So I decided to use the ServiceController API to stop the service when installation begins, install the files (overwriting the existing files), and start to service again. There is very little to the code, but here it is:</p>
  
  <p>Instantiate ServiceController:</p>
  
  <pre><code>try
  {
      service = new ServiceController(serviceName);
  }
  catch (InvalidOperationException ioe)
  {
      // ...
  }
  </code></pre>
  
  <p>Stopping the service:</p>
  
  <pre><code>if (service.Status != ServiceControllerStatus.Stopped)
  {
      service.Stop();
  }
  </code></pre>
  
  <p>Then wait for the service to be stopped and install the files:</p>
  
  <pre><code>service.WaitForStatus(ServiceControllerStatus.Stopped);
  // install files...
  </code></pre>
  
  <p>And lastly restart the service:</p>
  
  <pre><code>service.Start();
  </code></pre>
  
  <p>With this code, the <code>service.WaitForStatus()</code> method will just wait forever (or longer than I'm prepared to wait at least- up to an hour). The strange thing is that I can run this code, write <code>service.Status()</code> to a log, check the service manually to see that it has stopped, check the log and see that ServiceController thinks the service is still running.</p>
  
  <p>At first I thought that the issue was with <code>service.Stop()</code> so I tried creating a couple of <code>Process</code> objects that got the service PID and then killed the task, which stops the service instantly, but still <code>ServiceController</code> will not recognise that the service has stopped. If I remove the <code>service.WaitForStatus()</code> method from my code, an exception will be thrown since the installer is trying to overwrite a file that is in use by the service.</p>
  
  <p>Also, I've tried this with different services, but the result is always the same, leading me to believe that the issue is not with the service itself.</p>
  
  <p>Why is <code>ServiceController</code> not recognising that the service has stopped? Is there a solution or workaround to this problem? I'm working with <strong>.NET 2.0</strong>, so anything that requires higher is, unfortunately, not an option for me. Cheers.</p>