Jason
Jason

Reputation:

Executing sc.exe from .NET Process unable to start and stop service

I'm trying to restart the service from a remote machine. Here is my code. The problem is that I need to enter startinfo.filename = "sc.exe" since I'm putting "start /wait sc" this is causing an error. Here is my code, any thoughts. Also if anyone has any idea how to keep the cmd window open after this is ran so I could see the code that was ran that would be awesome.

string strCommandStop1;
string strCommandStop2;
string strCommandStart1;
string strCommandStart2;
string strServer = "\\" + txtServerName.Text;
string strDb1 = "SqlAgent$" + txtInsName.Text;
string strDb2 = "MSSQL$" + txtInsName.Text;

strCommandStop1 = @"start /wait sc " + strServer + " Stop " + strDb1;
strCommandStop2 = @"start /wait sc " + strServer + " Stop " + strDb2;
strCommandStart1 = @"start /wait sc " + strServer + " Start " + strDb2;
strCommandStart2 = @"start /wait sc " + strServer + " Start " + strDb1;

try
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;

    startInfo.Arguments = strCommandStop1;
    startInfo.Arguments = strCommandStop2;
    startInfo.Arguments = strCommandStart1;
    startInfo.Arguments = strCommandStart2;
    startInfo .FileName = "sc.exe";

    Process.Start(startInfo);

}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}

Upvotes: 0

Views: 3107

Answers (4)

Adrian Pascalin
Adrian Pascalin

Reputation: 71

The console can remain open if you use cmd /k and without the start which seems to open a new cmd. so it should be something like cmd /k sc.exe " + server + " Stop " + database;

Upvotes: 0

Stefan Egli
Stefan Egli

Reputation: 17018

Why don't you use the ServiceController class? This way you would have much better control of what is going on.

Upvotes: 3

chsh
chsh

Reputation: 2394

I think your problem is that your startInfo object is going to actually call:

sc.exe start /wait sc <strServer> Start <strDb1>

Also, is there a particular requirement you have to use sc instead of using the ServiceController class from the System.ServiceProcess library?

Upvotes: 0

Kim Gr&#228;sman
Kim Gr&#228;sman

Reputation: 7586

"start" is an intrinsic command in the cmd.exe shell, so use cmd.exe as Filename;

ProcessStartInfo si = new ProcessStartInfo();
si.CreateNoWindow = true;
si.Arguments = "/c start /wait sc.exe " + server + " Stop " + database;
si.FileName = "cmd.exe";
Process.Start(si);

Also, your successive re-assignment of the Arguments property looks strange. You need to call Process.Start for each command-line you want to execute.

Upvotes: 0

Related Questions