How to execute a command via command-line and wait for it to be done

Even shorter:

Process.Start("cmd.exe", @"/k java -jar myJava.jar").WaitForExit();

This works because the static method Process.Start returns a Process object. Then you can call the WaitForExit method directly on it, without even storing it in a local variable.


Use the Process.WaitForExit Method:

 public void runCmd()
 {
    String command = @"/k java -jar myJava.jar";
    ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
    cmdsi.Arguments = command;
    Process cmd = Process.Start(cmdsi);
    cmd.WaitForExit();    
 }
.
.
.
 runCmd();        
 MessageBox.Show("This Should popup only when runCmd() finishes");

You could use WaitForExit().

Note:

  1. WaitForExit(int milliseconds) to wait the specified number of milliseconds for the associated process to exit.
  2. WaitForExit() wait indefinitely for the associated process to exit.
public void runCmd()
{
  String command = @"/k java -jar myJava.jar";
  ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
  cmdsi.Arguments = command;
  Process cmd = Process.Start(cmdsi);
  cmd.WaitForExit(); //wait indefinitely for the associated process to exit.
}
.
.
.
runCmd();           //first command, takes 2 minutes to finish
MessageBox.Show("This Should popup only when runCmd() finishes");

Tags:

C#