I'm trying to execute a batch file in C#, but I'm not getting any luck doing it.
I've found multiple examples on the Internet doing it, but it is not working for me.
public void ExecuteCommand(string command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
}
The command string contains the name of the batch file (stored in system32
) and some files it should manipulate. (Example: txtmanipulator file1.txt file2.txt file3.txt
). When I execute the batch file manually, it works correctly.
When executing the code, it gives me an **ExitCode: 1** (Catch all for general errors)
What am I doing wrong?
This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:
* EDIT *
Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).
This does work if the batch file is not located in
C:\Windows\System32
. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.* EDIT 2 * It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before
WaitForExit
or by reading bothstderr
andstdout
synchronously one after the other.This should not happen if using the asynchronous read methods instead, as in the following example:
It works fine. I tested it like this:
I commented out turning off the window so I could SEE it run.
Have you tried starting it as an administrator? Start Visual Studio as an administrator if you use it, because working with
.bat
files requires those privileges.After some great help from steinar this is what worked for me:
this simple line will execute the batch file.