如何等待批处理文件执行完毕

6

我正在编写一个程序,在其中需要启动cmd并启动批处理文件。问题在于我使用了 MyProcess.WaithForexit();,我认为它不会等待批处理文件处理完成,而只是等待cmd关闭。到目前为止,我的代码如下:

System.Diagnostics.ProcessStartInfo ProcStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd");
    ProcStartInfo.RedirectStandardOutput = true;
    ProcStartInfo.UseShellExecute = false;
    ProcStartInfo.CreateNoWindow = false;
    ProcStartInfo.RedirectStandardError = true;
    System.Diagnostics.Process MyProcess = new System.Diagnostics.Process();
    ProcStartInfo.Arguments = "/c start batch.bat ";
    MyProcess.StartInfo = ProcStartInfo;
    MyProcess.Start();
    MyProcess.WaitForExit();

我需要等到批处理文件完成。我该怎么做?


6
移除 start 命令并运行批处理,然后返回结果。 - CodeCaster
2个回答

8

对我来说,这真的很有效:

System.Diagnostics.Process.Start("myBatFile.bat").WaitForExit();

如Milton所说,在批处理文件的末尾添加“exit”可能是个好主意。
干杯。

1
这应该是被接受的答案,非常简单而且对我所寻找的非常有效。+1 - Mister SirCode

3

start命令有一些参数,可以使其等待启动的程序完成。按照下面的示例编辑参数,传递“/wait”:

ProcStartInfo.Arguments = "/c start /wait batch.bat ";

我建议您让批处理文件退出cmd环境,因此在批处理文件的结尾处放置一个“exit”命令。
@echo off
rem Do processing
exit

这应该可以实现所需的行为。

3
在批处理文件末尾添加“exit”非常重要。 - Sarah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接