首页 > 解决方案 > 使用 Process.WaitForExit 后代码继续运行

问题描述

我目前正在尝试编写一个GUI

首先,我运行一个命令来启动图像的实际转换。在该方法之后,我想将转换后的文件移动到不同的文件夹MoveFile()

问题是程序不会等待 CMD 进程完成,而是要立即移动文件。当我调试程序并真正让它完成 CMD 命令时,文件将被毫无问题地移动。

从网上阅读我需要使用.WaitForExit(),但它似乎并没有做太多。

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

运行命令()

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

有帮手吗?

标签: c#

解决方案


发现问题。

必须在 CMD 命令的实际完成和文件的移动之间放置一个小 Thread.Sleep。


推荐阅读