Executing Batch File in C#

前端 未结 12 1782
有刺的猬
有刺的猬 2020-11-22 05:22

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

12条回答
  •  别跟我提以往
    2020-11-22 05:44

    With previously proposed solutions, I have struggled to get multiple npm commands executed in a loop and get all outputs on the console window.

    It finally started to work after I have combined everything from the previous comments, but rearranged the code execution flow.

    What I have noticed is that event subscribing was done too late (after the process has already started) and therefore some outputs were not captured.

    The code below now does the following:

    1. Subscribes to the events, before the process has started, therefore ensuring that no output is missed.
    2. Begins reading from outputs as soon as the process is started.

    The code has been tested against the deadlocks, although it is synchronous (one process execution at the time) so I cannot guarantee what would happen if this was run in parallel.

        static void RunCommand(string command, string workingDirectory)
        {
            Process process = new Process
            {
                StartInfo = new ProcessStartInfo("cmd.exe", $"/c {command}")
                {
                    WorkingDirectory = workingDirectory,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                }
            };
    
            process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("output :: " + e.Data);
    
            process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine("error :: " + e.Data);
    
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
    
            Console.WriteLine("ExitCode: {0}", process.ExitCode);
            process.Close();
        }
    

提交回复
热议问题