检查批处理脚本中的用户输入

时间:2017-02-07 15:20:32

标签: c#

Iam目前正在使用此方法启动批处理脚本(异步)

private void executor(string path)
{
    //Vars
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo(path);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);

    process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => 
    {
        //Handle Output
    });

    process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
    {
        //Handle Errors
    });

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();

    //Handle Exit
}

用户选择了脚本(将由我的程序执行)并可以运行它。但是用户可以选择包含pause - 命令的脚本。 这将导致死锁。 如何检查脚本是否需要用户输入?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我不再使用OutputDataReceived - 事件。

这是我新的(运作良好的)代码:

 private void executor(string path)
 {
    //Vars
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo(path);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);

    process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
    {
        //Handle Errors
    });

    process.BeginErrorReadLine();

    //Try read while script is running (will block thread until script ended)
    while (!process.HasExited)
        while (!process.StandardOutput.EndOfStream)
        {
            char c = (char)process.StandardOutput.Read();


            if (c == '\n')
            {
                _outputList.Add(_lastOutputStringBuilder.ToString());
                _lastOutputStringBuilder.Clear();

                //Handle Output
            }
            else
                _lastOutputStringBuilder.Append(c);

        }

    //Handle Exit
}

使用此代码,我可以存储最后一行(不能以换行符结尾),并可以检查“按一个键......”等行。