[英]Run interactive command line exe using c#
我可以使用process.start()
运行命令行进程。 我可以使用标准输入提供输入。 之后,当进程再次要求用户输入时,我的程序如何知道并将输入传递给该exe?
这里有一个例子 ,听起来与你需要的相似,使用Process.StandardInput
和StreamWriter
。
Process sortProcess;
sortProcess = new Process();
sortProcess.StartInfo.FileName = "Sort.exe";
// Set UseShellExecute to false for redirection.
sortProcess.StartInfo.UseShellExecute = false;
// Redirect the standard output of the sort command.
// This stream is read asynchronously using an event handler.
sortProcess.StartInfo.RedirectStandardOutput = true;
sortOutput = new StringBuilder("");
// Set our event handler to asynchronously read the sort output.
sortProcess.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
// Redirect standard input as well. This stream
// is used synchronously.
sortProcess.StartInfo.RedirectStandardInput = true;
sortProcess.Start();
// Use a stream writer to synchronously write the sort input.
StreamWriter sortStreamWriter = sortProcess.StandardInput;
// Start the asynchronous read of the sort output stream.
sortProcess.BeginOutputReadLine();
Console.WriteLine("Ready to sort up to 50 lines of text");
String inputText;
int numInputLines = 0;
do
{
Console.WriteLine("Enter a text line (or press the Enter key to stop):");
inputText = Console.ReadLine();
if (!String.IsNullOrEmpty(inputText))
{
numInputLines ++;
sortStreamWriter.WriteLine(inputText);
}
}
希望有所帮助
如果我理解正确,我认为您应该可以通过使用RedirectStandardOutput和RedirectStandardInput重定向标准输入/输出来实现此目的。
WinSCP项目有一个C#示例,用于使用这种方式与它进行通信。 你可以在这里找到它: 在.NET中的SFTP文件传输 (尽管这个示例只收集输出而根本不使用它,但技术应该是相同的。)
你想查找IPC。 正如罗伯特上面所示,.NET中的Process
类可以帮助你。 但专门针对您的问题(如何知道何时写入数据):您不能。 不是一般的。
如果您知道所需的输入(例如“yyy”),则可以在创建的过程的STDIN
中提供它。 您不必等待程序请求此信息:它只是在需要数据时从STDIN
读取。
如果需要处理程序输出以决定写入STDIN
,请尝试读取STDOUT
进程。 你可能会遇到冲洗问题,但......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.