Stopping Windows Service from C# code doesn't work - c#

My code has to stop a service. I'm using the code below:
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.UseShellExecute = true;
processInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + #"\System32\cmd.exe";
processInfo.Arguments = "sc stop SERVICENAME";
processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
processInfo.Verb = "runas"; //The process should start with elevated permissions
Process process = new Process() { EnableRaisingEvents = true, StartInfo = processInfo };
process.Start();
process.WaitForExit();
I then check the service state from a CMD window (manually, not in my program) with the following command: sc SERVICENAME query. But the state is still RUNNING.
When I stop it opening cmd as Administrator and executing the same commands (sc stop SERVICENAME), it just works.
Any thoughts about why it doesn't work from my code?

With C# and .NET, it is better if you use the ServiceController class like this:
ServiceController controller = new ServiceController("SERVICENAME");
controller.Stop();

Executing cmd.exe with sc stop SERVICENAME as arguments won't do anything. It will only start the command prompt.
To fix your problem, simply execute sc.exe directly, passing stop SERVICENAME as the arguments.
// ...
processInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "sc.exe");
processInfo.Arguments = "stop SERVICENAME";
// ...

Related

Working with the command prompt in C#

I am working on a project of remotely receiving commands from a server, but I am facing a problem when working with the command prompt locally. Once I get it working locally, then I will move to remote communication.
Problem:
I have to completely hide the console, and client must not see any response when the client is working with the command line but it will show a console for a instance and then hide it.
I had to use c# to send a command to cmd.exe and receive the result back in C#. I have done it in one way by setting the StandardOutput... and input to true.
The commands are not working. For example, D: should change the directory to D and it does, but after that, if we use dir to see the directories in D, it does not show the appropriate directories.
Here is my code:
First Method
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C " + textBoxInputCommand.Text + " >> " + " system";
process.StartInfo = startInfo;
process.Start();
Second Method
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + textBoxInputCommand.Text);
procStartInfo.WorkingDirectory = #"c:\";
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = true;
procStartInfo.UseShellExecute = false;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
richTextBoxCommandOutput.Text += result;
I want the program to run as administrator because the exe it generates does not run commands when it runs from the C drive.
Try not to run the commands by passing them to cmd instead write the commands passed by the client to a.bat file execute the .bat. file from your program this will probably hide your command prompt window.
You can also use process.OutputDataRecieved event handler to do anything with the output.
If you want to execute command using administrator rights you can use runascommand. It is equivalent to the sudo command in Linux. Here is a piece of code may be it will help you
var process = new Process();
var startinfo = new ProcessStartInfo(#"c:\users\Shashwat\Desktop\test.bat");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataRecieved += DoSomething;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
//Event Handler
public void DoSomething(object sener, DataReceivedEventArgs args)
{
//Do something
}
Hope it helps you.
You could hide command prompt window by adding this line of code:
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
or do not create it at all
startInfo.CreateNoWindow = true;
Here can be found a few awarding solutions:
Run Command Prompt Commands

Log Process execution

I am trying to restart a windows service from the same windows service with this piece of code
var proc = new Process();
var psi = new ProcessStartInfo();
psi.CreateNoWindow = true;
psi.FileName = "cmd.exe";
psi.Arguments = "/C net stop \"EmailService-3.1.0\ && net start \"EmailService-3.1.0\"";
psi.LoadUserProfile = false;
psi.UseShellExecute = false;
psi.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo = psi;
It is not working and I have no idea why, is there anything I can do to log or determine what is happening or get the output of what is happening when the net stop command is called?
You can redirect the output of the net stop command, but as per TomT's comment, this seems a very roundabout way to restart a service.
psi.Arguments = "/C net stop \"EmailService-3.1.0\" > C:\\svclog.txt "; //&& net start \"EmailService-3.1.0\"";
I can see a missing quotation mark after the name of your service in the stop command. Otherwise it can be a permission issue. Maybe the user with whom your service has logged in does not have enough privileges to stop a service.

Stop new command window opening each time command is executed

I have written a C# tool that will launch an application by running a command in the command prompt for me several times, one after the other. The piece of code doing this for me is as follows:
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
So I have this in a loop and all is good. However each time it executes a new command window is opened, which isnt ideal. Is there a way I can close the command window after the command has executed, or better still, not have the command window open at all? Any help is really appreciated!!
Yes, you have to use the ProcessStartInfo class for doing this:
Process.Start(
new ProcessStartInfo("CMD.exe", strCmdText)
{
CreateNoWindow = true
});
Use ProcessStartInfo to start the process (Start has an overload that takes a ProcessStartInfo).
Set the following properties:
var psi = new ProcessStartInfo("cmd.exe", strCmdText);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
ProcessStartInfo allows you to specify no window.
using (var p = new Process())
{
p.StartInfo = new ProcessStartInfo
{
FileName = "CMD.exe",
Arguments = strCmdText,
CreateNoWindow = true,
UseShellExecute = false
};
p.Start();
p.WaitForExit();
p.Close();
}

How to launch an external process in C#, using a cmd window

I am having trouble executing an external console application using Process.Start
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
When the argument that p generates executes, the external application crashes, although if I copy the exact same argument in a command line window it runs fine.
So my question instead how would I create a new instance of a command window and then add the command test.exe + s to run?
So effectively I am launching cmd and then adding my arguments on to it
If you want to run test.exe prm1 prm2 via cmd, use cmd.exe /c test.exe prm1 prm2. Though I don't really understand what this has to do with the crashes. Sounds like your problem is with test.exe - find out what's causing it to crash, and that will help you fix your C# code so that you don't need the cmd.
One of the places I would examine is the working directory. When you set it to "dump", are you sure the current directory is what you expect? Try using a full path first. It's possible that test.exe happens to be in the system path so it gets executed, but its working directory is not what it expects, and this causes it to crash.
try this:
ProcessStartInfo processToRunInfo = new ProcessStartInfo();
processToRunInfo.Arguments = "Arguments");
processToRunInfo.CreateNoWindow = true;
processToRunInfo.WorkingDirectory = "C:\\yourDir\\";
processToRunInfo.FileName = "test.exe";
//processToRunInfo.CreateNoWindow = true;
//processToRunInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = new Process();
process.StartInfo = processToRunInfo;
process.Start();
Process p = new Process();
p.StartInfo.WorkingDirectory = "/full/path/to/dump";
p.StartInfo.FileName = "/full/path/to/test.exe";
p.StartInfo.Arguments = s; // will call 'text.exe s'
p.Start();
Take a look at MSDN.
You need to Create an instance of the StartInfo class and user Start() such as
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(startInfo);
startInfo.Arguments = "www.example.com";
Process.Start(startInfo);
Try it!
Rewriting your code would look something like this:
ProcessStartInfo startInfo = new ProcessStartInfo("test.exe");
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
startInfo.WorkingDirectory = "dump";
startInfo.Arguments = "s";
Process.Start(startInfo);

Start command windows and run commands inside

I need to start the command window with some arguments and run more commands inside.
For example, launch a test.cmd and run mkdir.
I can launch the test.cmd with processstartinfo , but i am not sure how to run further commands. Can I pass further arguments to the test.cmd process?
How do I go about this?
Unable to add comments to answer... SO writing here.
Andrea, This is what I was looking for. However the above code doesnt work for me.
I am launching a test.cmd which is new command environment (like razzle build environment) and I need to run further commands.
psi.FileName = #"c:\test.cmd";
psi.Arguments = #"arg0 arg1 arg2";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.StandardInput.WriteLine(#"dir>c:\results.txt");
p.StandardInput.WriteLine(#"dir>c:\results2.txt");
You can send further commands to cmd.exe using the process
standard input. You have to redirect it, in this way:
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = new Process {StartInfo = startInfo};
process.Start();
process.StandardInput.WriteLine(#"dir>c:\results.txt");
process.StandardInput.WriteLine(#"dir>c:\results2.txt");
process.StandardInput.WriteLine("exit");
process.WaitForExit();
Remember to write "exit" as your last command, otherwise the cmd process doesn't terminate correctly...
The /c parameter to cmd.
ProcessStartInfo start = new ProcessStartInfo("cmd.exe", "/c pause");
Process.Start(start);
(pause is just an example of what you can run)
But for creating a directory you can do that and most other file operations from c# directly
System.IO.Directory.CreateDirectory(#"c:\foo\bar");
Start a cmd from c# is useful only if you have some big bat-file that you don't want to replicate in c#.
What are you trying to achieve? Do you actually need to open a command window, or do you need to simply make a directory, for example?
mkdir is a windows executable - you can start this program in the same way you start cmd - there's no need to start a command window process first.
You could also create a batch file containing all the commands you want to run, then simply start it using the Process and ProcessStartInfo classes you're already using.
How come this doesn't work?
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.StandardInput.WriteLine(#" dir");
process.WaitForExit();

Categories

Resources