developer
developer

Reputation: 1673

XCopy does not work with UseShellExecute = false

I am trying to run a Batch file from .net/c# using System.Diagnostics.Process. Somehow it does not execute xcopy command of the Batch file.

Sample Batch File:

#copy test to test2 including sub directories
xcopy c:\test\ c:\test2 

C# code:

    public void RunMSIBatchFile(string _workingDirectory, string batchFileName)
    {
        var process = new Process
        {
            StartInfo =
            {

                UseShellExecute = false,
                RedirectStandardOutput = true,
                WorkingDirectory = _workingDirectory,
                FileName = _workingDirectory + batchFileName,
                CreateNoWindow = true,
                RedirectStandardError = true
            }
        };

        process.OutputDataReceived += ProcessOutputDataReceived;
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit(Convert.ToInt32(CommandTimeOut.TotalMilliseconds));
    }

If I change UseShellExecute to true then it works but then there seems to be no way to capture standard output.

Has anyone faced such problem?

Upvotes: 1

Views: 2928

Answers (1)

Iridium
Iridium

Reputation: 23721

I've tested your exact code, and appear to be able to receive data just fine. However, since the read occurs asynchronously, it is possible for WaitForExit(...) to return before you have read all of the data. It appears that the end of the data is signalled by the Data property of the DataReceivedEventArgs passed to the OutputDataReceived event handler being null.

It is also worth noting that if xcopy requests input from the user (e.g. in the case of a file with the same name existing in the destination) it appears that no data is returned. You may want to check for this in your batch file, or also handle data from the Standard Error stream.

Upvotes: 1

Related Questions