在 C# 中启动批处理文件,然后等待它退出,然后再继续

本文关键字:然后 退出 再继续 等待 启动 批处理文件 | 更新日期: 2023-09-27 18:34:31

问题是 WaitForExit 不会等到批处理文件退出。 它几乎马上就回来了。

我正在按如下方式启动我的批处理文件:

            ProcessStartInfo startInfo = new ProcessStartInfo(batchFile);
            startInfo.UseShellExecute = true;
            startInfo.Arguments = arguments;
            using (Process p = Process.Start(startInfo))
            {
                p.WaitForExit();
            }

我尝试过有和没有UseShellExecute.

在 C# 中启动批处理文件,然后等待它退出,然后再继续

您可以尝试使用"/c yourbatchfile"作为命令行参数运行cmd。

似乎您可以重定向StdOut并读取它直到它关闭。

从这个类似的问题中得出了这个想法。

调整您的代码段,这将是:

ProcessStartInfo startInfo = new ProcessStartInfo(batchFile);
//startInfo.UseShellExecute = true;
startInfo.Arguments = arguments;
startInfo.RedirectStandardOutput = true;
Process p = Process.Start(startInfo);
String output = proc.StandardOutput.ReadToEnd();