How to stop the SQL Server service using C#

Asked

Viewed 155 times

4

I wonder if it is possible to stop SQL Server using C lines of code#.

I have a C# application and would like to add a button to stop the SQL service or the instance, so I can work with the files. mdf and . ldf either to making bakup or replacing. I know it is possible to stop manually through the Windows service manager but I want to do this in a practical way.

1 answer

7


I believe this way he will execute the CMD and run the stop command on the service make a test to see if it solves your problem.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/c net stop MSSQL$SQLEXPRESS";
process.StartInfo = startInfo;
process.Start();
  • 1

    I tested, but it didn’t work. Should he open the 'CMD' window? I used exactly the code you informed me changing only the name of the instance 'MSSQL$SQLEXPRESSPOS4'. I must make some other changes?

  • 1

    No, he won’t open the CMD because of that line startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 if you want the CMD to appear just comment on it. since it did not work do the test of the command net stop with your instance directly in the CMD and see if it will work.

  • 1

    I went straight to CMD and gave "System error 5. Access denied". I ran CMD as administrator and it worked. But even running my application as an administrator and it still doesn’t work. Would have some way my program run CMD as administrator?

  • 1

    process.StartInfo.Verb = "runas"; tries to add this command before .StartInfo = startInfo;

  • 1

    We’re almost there (laughs.). I commented on the line startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; to see exactly what was going on at the CMD. The CMD opens however the command is not typed inside it and is not executed, in the CMD window that opened I typed the code net stop MSSQL$SQLEXPRESSPOS4 and it worked. What can be?

  • 1

    haha missed a /c in this line startInfo.Arguments = "/c net stop MSSQL$SQLEXPRESS"; Add it and test it.

  • 1

    It worked!!! Thank you very much!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.