我正在使用 .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