Stop SQL Server - using C #

How can I use C # to stop SQL Server?

+4
source share
6 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 { // ... } } 
+10
source

Run from SqlCommand: SHUTDOWN WITH NOWAIT; . Advantages over other proposed solutions:

  • this requires DB priviledges (sysadmin / serveradmin), not OS privileges
  • works through any network firewall if T-SQL is enabled (no additional ports needed )
  • you do not need to determine the service name (MSSQL $ instancename)
  • works if the service starts from the console ( sqlservr -c , not starting the service)
+4
source

You tried

 Process.Start("net stop mssqlserver") 
+3
source

Try stopping the service.

 using System.ServiceProcess; 

...

 ServiceController controller = new ServiceController(); controller.MachineName = "."; controller.ServiceName = "MySqlServerInstance"; controller.Stop(); 
+2
source
 using System.Diagnostics; public static bool StopProcess(string name) { try { var process = Process.GetProcesses().SingleOrDefault(p => p.ProcessName == name); process.WaitForExit(); return true; } catch (Exception) { //throw; return false; } } 
0
source

If you do not want to use the ServiceController , you can kill the sqlservr process to kill the correct process.

 Process.GetProcesses().Where(x => x.ProcessName == "sqlservr").ToList().ForEach(x => x.Kill()); 
0
source

All Articles