How to wait until my batch file is finished

末鹿安然 提交于 2020-01-03 13:01:30

问题


I'm doing a program where I need to start cmd and there start up a batch file. The problem is that I'm using MyProcess.WaithForexit(); and I think it does not wait until the batch file processing is finished. It just waits until the cmd is closed. My code so far:

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();

I need to wait until the batch file is finished. How do I do that?


回答1:


The start command has arguments that can make it WAIT for the started program to complete. Edit the arguments as show below to pass '/wait':

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

I would also suggest that you want your batch file to exit the cmd envirionment so place an 'exit' at the end of the batch.

@echo off
rem Do processing
exit

This should achieve the desired behavior.




回答2:


This actually worked just fine for me:

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

As milton said, adding 'exit' at the end of your batch files is most likely a good idea.

Cheers



来源:https://stackoverflow.com/questions/30682629/how-to-wait-until-my-batch-file-is-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!