0

I'm currenty trying to write a GUI around

First I run a command to start the actual conversion of a image. After that method I want to move the converted file to a different folder by MoveFile().

The problem is that the program doesn't wait for the CMD process to be finished and it wants to move the file immediately. When I'm debugging the program and actually letting it finish the CMD command, the file will be moved with no problems.

From reading online I need to use .WaitForExit() but it doesn't seem to do much.

RunCommand(strCommand);
MoveFile(strDirectoryName + "\\" + strNewName, strDirectoryName + "\\0 - Preview\\" + strNewName);

RunCommand()

private void RunCommand(string CmdText) {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/c " + CmdText;
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
        }

Any helpers?

vahid tajari
  • 1,163
  • 10
  • 20
  • You can check whether file is locked or not. – Sandris B Aug 18 '20 at 11:52
  • Not sure what file you mean? However like I said, when I'm debugging it and going step by step it works. It can convert the file and move it When I just run it, it gives me an error that the MoveFile method cannot find the file, as it has not yet been created. – Jel Sadones Aug 18 '20 at 12:04
  • Maybe check if Process.HasExited is triggered? – Sandris B Aug 18 '20 at 12:08
  • Here is your ansfer -> https://stackoverflow.com/questions/40764093/process-waitforexit-not-waiting – Sandris B Aug 18 '20 at 12:10

2 Answers2

0

Found the issue.

Had to put a small Thread.Sleep between the actual finishing of the CMD command and the moving of the file.

0

you have 2 easy ways to do that: var1: you can use the static method

Process.Start(your_file, your_args).WaitForExit();

var2: Use the Exited event.

var p = new Process() { EnableRaisingEvents = true };
p.StartInfo.FileName = your_file;
p.StartInfo.Arguments = your_args;
p.Exited += (sender, e) =>
                {
                   your_next_step
                };
p.Start();

on P_Exited you can write the next step

Horus
  • 21
  • 4