2010-07-22 66 views
10

我可以运行使用process.start()的命令行进程。 我可以使用标准输入提供输入。之后,当进程再次要求用户输入时,我的程序如何知道并将输入传递给该exe文件?使用c运行交互式命令行exe#

+0

你可能感兴趣的[这篇文章](http://www.codeducky.org/process-handling-net)涵盖了许多错综复杂的工作。 NET进程,尤其是在处理输入和输出 – ChaseMedallion 2014-08-29 01:38:17

回答

10

有一个example here听起来类似于你需要什么,使用Process.StandardInputStreamWriter

 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); 
      } 
     } 

希望帮助

+0

再次感谢。但这是特定于sort.exe 我在运行时为每个用户生成exe文件。我不知道他会输入哪个节目。 – rajshades 2010-07-22 12:28:05

+0

我认为你可以使用“cmd.exe”而不是他们选择的可执行文件。这是一个黑客,但它可能完成这项工作 – 2010-07-22 12:35:49

+0

亲爱的罗伯特·u能PLZ解释如何使用CMD.EXE我的问题 – rajshades 2010-07-23 05:07:41

2

如果我理解正确,我认为您应该可以通过使用RedirectStandardOutputRedirectStandardInput重定向标准输入/输出来完成此操作。

WinSCP项目有一个C#示例,用于如何使用这种方式与它进行通信。你可以在这里找到它:SFTP file transfers in .NET(虽然此示例仅收集输出,而不使用它所有,但该技术应该是一样的。)

+0

谢谢你的答复。我尝试过这个。但是要求用户输入的过程不是预定义的。该方案是像 1.我想设计在线compliler为C# 2.我可以使用代码创建该程序n cretae exe文件 3.现在我想通过C#运行该exe文件 4.用户可以编写任何类型的在diff阶段需要用户输入的程序。 希望你能理解整个场景 – rajshades 2010-07-22 12:21:18

+0

@rajshades:我会认为这会是类似的,但不是一次性发送所有命令,而是发送命令,读取输出,发送下一个命令等我虽然没有测试过。作为一个普遍的说明,如果你正在创建这个exe文件,你能不能尝试给它一些更好的方式来与它进行通信(WCF,TCP/IP协议,命名管道等)? – 2010-07-22 12:49:48

1

你想查找IPC。正如罗伯特所示,.NET中的Process类将帮助您。但专门为你的问题(如何知道何时写数据):你不能。不是一般的。

如果您知道所需的输入(例如“yyy”),则可以在创建的过程的STDIN中提供。您不必等待程序请求这些信息:它只会在需要数据时从STDIN中读取。

如果您需要处理程序输出以决定要写入STDIN的内容,请尝试阅读进程STDOUT。你可能会遇到冲洗的问题,虽然...