Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop SQL Server - using C#

Tags:

c#

sql

sql-server

How can I use C# to stop SQL Server?

like image 293
kartal Avatar asked Oct 06 '10 17:10

kartal


4 Answers

From http://www.csharp-examples.net/restart-windows-service/

public static void StopService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
  }
  catch
  {
    // ...
  }
}
like image 141
D'Arcy Rittich Avatar answered Sep 28 '22 06:09

D'Arcy Rittich


Execute from a SqlCommand: SHUTDOWN WITH NOWAIT;. The advantages over the other proposed solutions:

  • this requires DB priviledges (sysadmin/serveradmin), not OS privileges
  • works over any network firewall as long as T-SQL is let in (no extra ports needed)
  • you don't need to figure out the service name (MSSQL$instancename)
  • works if the service is started from console (sqlservr -c, not service start)
like image 25
Remus Rusanu Avatar answered Sep 28 '22 07:09

Remus Rusanu


Try stopping the service.

using System.ServiceProcess;

...

ServiceController controller  = new ServiceController();

controller.MachineName = ".";
controller.ServiceName = "MySqlServerInstance";


controller.Stop();
like image 23
Wix Avatar answered Sep 28 '22 06:09

Wix


Have you tried

Process.Start("net stop mssqlserver")
like image 27
Adam Straughan Avatar answered Sep 28 '22 07:09

Adam Straughan