C#进程未接收输入

本文关键字:输入 进程 | 更新日期: 2023-09-27 18:25:10

我有一个调用fortran可执行文件的进程。可执行文件向用户请求文件并执行操作以找到解决方案。如果在文件中找到多个解决方案,程序会询问用户是否希望找到最理想的解决方案,基本上是程序的2个输入。可执行文件然后生成一个文本文件,该文件提供程序的结果。

进程可以运行,但是不会生成生成的文本文件。此外,当我检查应用程序的输出时,消息提示("Enter a file")是字符串中唯一存储的内容,它不包括最佳解决方案的辅助提示("你想找到最理想的解决方案吗?")。有人能告诉我为什么会发生这种事吗?谢谢

Process exeProcess = new Process();
exeProcess.StartInfo.FileName = "sdf45.exe";
exeProcess.StartInfo.UseShellExecute = false;
exeProcess.StartInfo.RedirectStandardError = true;
exeProcess.StartInfo.RedirectStandardInput = true;
exeProcess.StartInfo.RedirectStandardOutput = true;
exeProcess.Start();        
//input file                
exeProcess.StandardInput.WriteLine(Path.GetFileName(filePath));            
//find optimal solution
exeProcess.StandardInput.WriteLine("Y");
string output = exeProcess.StandardOutput.ReadToEnd();            
exeProcess.WaitForExit();

C#进程未接收输入

我的猜测是,这一行在FORTRAN进程有机会读取输入之前就已经执行(并返回)了:

string output = exeProcess.StandardOutput.ReadToEnd();

在这种情况下,我不能100%确定ReadToEnd();在无界流上的结果是什么。正如Jon Skeet在这里提到的那样,正确的方法是在另一个线程中从stdout读取,或者更好的是异步读取,如本文所述:http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline.aspx

为了子孙后代,一个粗略的例子:

var outputReader = new Thread(ReadOutput);
outputReader.Start(exeProcess);

ReadOutput的定义如下:

public void ReadOutput(Object processState) {
    var process = processState as Process;
    if (process == null) return;
    var output = exeProcess.StandardOutput.ReadToEnd();
    // Do whetever with output
}

制作您的初始方法:

Process exeProcess = new Process();
exeProcess.StartInfo.FileName = "sdf45.exe";
exeProcess.StartInfo.UseShellExecute = false;
exeProcess.StartInfo.RedirectStandardError = true;
exeProcess.StartInfo.RedirectStandardInput = true;
exeProcess.StartInfo.RedirectStandardOutput = true;
exeProcess.Start();        
//input file                
exeProcess.StandardInput.WriteLine(Path.GetFileName(filePath));            
//find optimal solution
exeProcess.StandardInput.WriteLine("Y");
var outputReader = new Thread(ReadOutput);
outputReader.Start(exeProcess);
exeProcess.WaitForExit();
outputReader.Join();

这很难说,但我认为您需要向可执行文件传递一个参数,比如这个

Process exeProcess = new Process();
exeProcess.StartInfo.FileName = "sdf45.exe";
exeProcess.StartInfo.UseShellExecute = false;
exeProcess.StartInfo.RedirectStandardError = true;
exeProcess.StartInfo.RedirectStandardInput = true;
exeProcess.StartInfo.RedirectStandardOutput = true;
exeProcess.StartInfo.Arguments = Path.GetFileName(filePath); //pass file path to EXE
exeProcess.Start();

希望这能帮助