开发者

Stop SQL Server - using C#

How can I use C# to stop开发者_Python百科 SQL Server?


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
  {
    // ...
  }
}


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)


Try stopping the service.

using System.ServiceProcess;

...

ServiceController controller  = new ServiceController();

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


controller.Stop();


Have you tried

Process.Start("net stop mssqlserver")


If you don't want to use ServiceController you can kill sqlservr process to kill the right process.

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜