2012-02-20 26 views
2

我已經調用一個FORTRAN可執行的處理。可執行文件向用戶請求一個文件並執行操作以查找解決方案。如果在文件中找到多個解決方案,程序會詢問用戶是否想要找到最佳解決方案,基本上該程序有兩個輸入。然後可執行文件生成一個提供程序結果的文本文件。C#過程不接收輸入

過程是能夠運行,但不會產生結果文本文件。此外,當我檢查應用程序的輸出,信息提示(「輸入文件」)是存儲在字符串中的唯一的事情,它不包含最優解的二次提示(「你想找到最優解決方案?「)。任何人都可以給我一個想法,爲什麼會發生這種情況?謝謝。

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(); 
+0

如何執行請求來自用戶的文件嗎? – Tigran 2012-02-20 20:50:28

+0

所以我看到你在不閱讀它的情況下重定向標準錯誤。如果程序寫很多標準錯誤,這可能會導致問題。 – Servy 2012-02-20 20:52:03

+0

可執行文件要求提供與可執行文件位於同一目錄中的文件的名稱。 – BeingIan 2012-02-20 20:52:57

回答

0

這很難說,但我假定,你需要一個參數傳遞到可執行文件,這樣

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

希望這有助於

+1

從OP看來,文件名似乎是通過stdin(在提示後)傳遞的,而不是參數。 – 2012-02-20 20:54:03

+0

@ChrisShain:實際上並不十分清楚*那*點。如果歐普澄清它會好起來的。 – Tigran 2012-02-20 21:13:45

1

我的猜測是,這條線是FORTRAN過程甚至有機會來讀取輸入之前執行(和返回):

string output = exeProcess.StandardOutput.ReadToEnd(); 

我不是100%肯定什麼ReadToEnd();無界流的結果是在這種情況下。做正確的方法,如通過喬恩斯基特here提到的,是從標準輸出在另​​一個線程讀取或更好的異步,如記錄在這裏: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(); 
+0

雖然從標準讀出並不是一個壞主意,但我認爲這不太可能是OP的問題。ReadToEnd是阻塞的,所以它不會返回,直到程序發送它是流結束消息,在程序準備退出之前程序不會發送消息(除非某些平均/無能的程序員在仍然存在時將EOS標記寫入標準輸出更多的內容寫出來)。 – Servy 2012-02-20 22:28:44