c# - 如何识别流程是否需要输入?

标签 c# process system.diagnostics redirectstandardoutput

<分区>

我正在使用 .NET Framework 中的 System.Diagnostics.Process 类运行命令提示符实用程序。此命令提示符实用程序在某些情况下可能需要一些用户输入,有时它也可以在不需要用户输入任何内容的情况下完成任务。 这是我为运行此过程所做的工作:

    var process = new Process();
    process.StartInfo = new ProcessStartInfo([PATH_TO_EXE], arguments);
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;
    process.Start();

问题是我不知道如何确定这个过程是否需要输入?

最佳答案

我能找到的唯一有效的方法。无论 react 多短或多长。在您发送这样的命令后也添加回声。而不仅仅是检查回声以了解何时停止等待。

var process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;

process.StartInfo.FileName = Settings.MongoPath;

// Redirects the standard input so that commands can be sent to the shell.
process.StartInfo.RedirectStandardInput = true;

process.StartInfo.Arguments = ConnString;

process.Start();

// this is key, this returns 1 once previous command in argument is done executing
process.StandardInput.WriteLine("{ping:1}");

var current_line = string.Empty;
var OutputList = new List<string>();
while (!process.StandardOutput.EndOfStream)
{
    current_line = process.StandardOutput.ReadLine();
    if (current_line == "1")
    {
        // command is done executing 
        break;
    }

    OutputList.Add(current_line);
}

// contains all of the out put of the command
OutputList

关于c# - 如何识别流程是否需要输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30162562/

相关文章:

java - 从 Java 代码调用 C 可执行文件后没有得到任何输出

c# - Process.Start() 中的错误——系统找不到指定的文件

.net - 有没有扩展 System.Diagnostics.Trace 的库?

c# - 如何以编程方式获取当前的跟踪开关?

c# - 如何在 NEST 中禁用驼峰式 Elasticsearch 字段名称?

c# - 以编程方式将 pkcs12 的私钥安装到 Linux 上的 Mono Cert Store

C# Windows 窗体被任务管理器杀死......有没有办法运行关机功能?

c# - "File not found"使用 Process.Start() 启动 system32\winsat.exe 时出错

c# - 在 .net 中的两个项目之间共享 dll

javascript - 基于 ASP 复选框隐藏 div