2017-10-06 51 views
0

我正在嘗試與使用Fortran編寫的舊CLI應用程序進行交互。在C#中使用CLI應用程序的標準輸出始終爲空

問題是,我甚至無法讀取程序的輸出。閱讀各種SO問題我試了下面的代碼:

// Start a new process 
Process p = new Process(); 

// Redirect output and error 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardError = true; 

// Exe path 
p.StartInfo.FileName = @"C:\path\to\exe"; 

// Hook received events 
p.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data); 
p.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data); 

p.Start(); 

p.BeginOutputReadLine(); 
p.BeginErrorReadLine(); 

但是..沒有任何反應。使用System32文件夾中的通用ipconfig.exe替換Fortran exe實際上可以工作,並且我可以讀取輸出。

更新:而在VS中來回測試我注意到,當我關閉窗口時,正確的輸出顯示幾分之一秒。 看來,輸出在那裏,但直到我關閉窗口才顯示。

我錯過了什麼嗎?

+0

爲什麼'p.OutputDataReceived + =(sender,e)=> Console.WriteLine(e.Data);'重複兩次? – mjwills

+0

ErrorDataReceived,希望。有一些脾氣暴躁的程序也需要RedirectStandardInput = true才能正常工作,xcopy.exe是一個臭名昭着的例子。接下來要嘗試。 –

+0

@mjwills哎呀,它是'ErrorDataReceived'。對不起。 @HansPassant謝謝,會試一試。編輯:嘗試,不幸的是沒有改變,但我注意到了一些。請參閱更新中的問題。 –

回答

0

Process.BeginOutputReadline()可能會阻塞,直到它收到一個新的行char。我會嘗試直接讀取OutputStream對象的byte-by-byte。

+0

我嘗試用'while(!p.StandardOutput.EndOfStream){Console.WriteLine(p.StandardOutput.ReadLine();}替換BeginOutputReadline(),它的行爲與原始一樣。輸出僅顯示一個分數當關閉窗戶時,我開始認爲我正在做一件非常愚蠢的事情。 –

相關問題