0

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

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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. Thanks Tony

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.