检查CMD是否在用作进程时处于空闲状态

时间:2017-07-14 15:48:56

标签: c# cmd process

问题:传递给CMD实用程序的文件数量问题。

所需解决方案:在增加循环之前能够检查CMD是否已完成转换文件的方法。

我正在使用C#中的用户界面在CMD中运行实用程序。该实用程序将音频文件从.vce转换为.wav。如果选择的文件多于30个,则该实用程序会不堪重负并停止工作。在循环递增之前,如何检查它是否已完成一次文件转换? .WaitForExit().WaitForProcessIdle()都不起作用。

//arguements are a list of files selected by the user for conversion, 
//the folder to save the converted files in, and the path that the 
//current files are under
public static void convertVCE(List<string> files, string newPath, string filePath)
{
    Process process1 = new Process();
    process1.StartInfo.FileName = "cmd.exe";
    process1.StartInfo.CreateNoWindow = false;
    process1.StartInfo.RedirectStandardInput = true;
    process1.StartInfo.RedirectStandardOutput = true;
    process1.StartInfo.UseShellExecute = false;
    process1.Start();
    //move to directory where the utility is
    process1.StandardInput.WriteLine("cd \\Program Files (x86)\\NMS Utilities");
    process1.StandardInput.Flush();

    //loop to convert each selected file
    for (int i = 0; i < files.Count; i++)
    {
        if (files[i].EndsWith(".vce"))
        {
            string fileName = Path.Combine(filePath, files[i]);
            string newFileName = Path.Combine(newPath, files[i]).Replace(".vce", "");

            process1.StandardInput.WriteLine(string.Format("vcecopy.exe {0} {1}.wav", fileName, newFileName));
            process1.StandardInput.Flush();
        }
    }
    process1.StandardInput.Close();
    Console.WriteLine(process1.StandardOutput.ReadToEnd());
    process1.WaitForExit();
}

1 个答案:

答案 0 :(得分:1)

您正在创建不需要的 cmd.exe 进程。您需要创建 vcecopy.exe 进程并等待它们在启动时完成。以下几点(我现在无法对此进行测试,我在内存上编码,但您应该明白这一点):

var vceCopyStartInfo = new StartInfo();
vceCopyStartInfo.CreateNoWindow = true;
vceCopyStartInfo.UseShellExecute = false;
vceCopyStartInfo.WorkingDirectory = "\\Program Files (x86)\\NMS Utilities";
vceCopyStartInfo.FileName = "vcecopy.exe";

for (int i = 0; i < files.Count; i++)
{
    if (files[i].EndsWith(".vce"))
    {
        string fileName = Path.Combine(filePath, files[i]);
        string newFileName = Path.Combine(newPath, files[i]).Replace(".vce", "");
        //some applications need arguments in quotes, try it if this doesn't work.
        vceCopyStartInfo.Arguments = string.Format("{0} {1}.wav", fileName, newFileName));

        using (var vceCopyProcess = Process.Start(vceCopyStartInfo))
        {
            vceCopyProcess.WaitForExit();
            //if vcecopy doesn't exit by itself when it finishes, try WaitForProcessIdle
        }
    }
}