tags:

views:

183

answers:

1

Hello, 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

+2  A: 

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.

Hans Passant
That was it!! Thank you. The code above as well and my code both work now. I did noticed that other commands were executed correctly. Just xcopy was not working.ThanksTony
tony