I need to run Dos commands within a class. My problem is that the redirect options seem to prevent the command from running.
Here is my code:
public static int executeCommand(string cmd)
{
System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C " + cmd);
int exitCode = 0;
//processStartInfo.RedirectStandardError = true;
//processStartInfo.RedirectStandardOutput = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
System.Diagnostics.Process process =
System.Diagnostics.Process.Start(processStartInfo);
process.WaitForExit(); //wait for 20 sec
exitCode = process.ExitCode;
//string stdout = process.StandardOutput.ReadToEnd();
//string stderr = process.StandardError.ReadToEnd();
process.Close();
return exitCode;
}
When I call xcopy:
if (executeCommand("xcopy.exe " + "/E /I /R /Y /Q c:\\temp\\*.* e:\\temp\\b1\\ ") != 0)
Log.Error("Error detected running xcopy ");
The method correctly runs xcopy. If I want to redirect the SDTOUT and STDERR, the method returns 0 as well but xcopy didn’t really run.
In other words, this doesn’t work:
public static int executeCommand(string cmd)
{
System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo("CMD.exe", "/C " + cmd);
int exitCode = 0;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
System.Diagnostics.Process process =
System.Diagnostics.Process.Start(processStartInfo);
process.WaitForExit(); //wait for 20 sec
exitCode = process.ExitCode;
string stdout = process.StandardOutput.ReadToEnd();
string stderr = process.StandardError.ReadToEnd();
process.Close();
return exitCode;
}
Any idea why?
Thanks
tony
It is quirk of xcopy.exe, you must redirect stdin as well. Check this thread for my original diagnostic. No need to use cmd.exe btw, just call xcopy directly.