title: How to start all stop SQL Server Services using C#
body: <p>How to start all stop SQL Server services using C#?</p>
  
  <p>I am using this code but it is not working properly and show following error message :</p>
  
  <blockquote>
    <p>Cannot open MSSQL$SQLEXPRESS service on computer '.'.</p>
  </blockquote>
  
  <p>Code:</p>
  
  <pre><code>public string RestartService(string serviceName, int timeoutMilliseconds)
  {
      string status= string.Empty;
  
      ServiceController service = new ServiceController(serviceName);
  
      try
      {
           int millisec1 = Environment.TickCount;
           TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
           //service.Stop();
           //service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
  
           // count the rest of the timeout
           int millisec2 = Environment.TickCount;
           timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
  
           service.Start();
           service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  
           status = service.Status.ToString();
      }
      catch (Exception ex)
      {
          status = ex.Message;
      }
  
      return status;
  }
  </code></pre>
  
  <p>I want to use SQL Server service in window service to check if SQL Server is running or not. If it not running, then I want to start server first and then do next work.</p>