2009-11-09 93 views
1

我正在嘗試將可執行控制檯應用程序的輸出轉換爲另一個。準確地說,我想要做什麼的一個小概述:從另一個可執行文件獲取輸出

我有一個可執行文件,我不能編輯,也沒有看到它的代碼。它在執行時寫入一些(很坦白地說)線到控制檯。

現在我想編寫另一個可執行文件來啓動上面的代碼並讀取它寫入的內容。

看起來很簡單給我,所以我就開始編碼,但結束了一個錯誤信息說StandardOut has not been redirected or the process hasn't started yet.

我嘗試使用這個還挺結構(C#):

Process MyApp = Process.Start(@"C:\some\dirs\foo.exe", "someargs"); 
MyApp.Start(); 
StreamReader _Out = MyApp.StandardOutput; 

string _Line = ""; 

while ((_Line = _Out.ReadLine()) != null) 
    Console.WriteLine("Read: " + _Line); 

MyApp.Close(); 

我可以打開可執行文件它也會打開裏面的內容,但一旦讀取返回的值,應用程序就會崩潰。

我在做什麼錯?

+0

您可能感興趣的我對這個問題的答案:http://stackoverflow.com/questions/1096591 /如何隱藏cmd-window-while-running-a-batch-file/1096626#1096626 – 2009-11-09 12:47:21

回答

6

查看Process.StandardOutput屬性的文檔。您將需要設置一個布爾值,指示您希望流重定向以及禁用shell執行。從文檔

注:

要使用StandardOutput,你必須設置的ProcessStartInfo .. :: UseShellExecute爲false,並且必須設置的ProcessStartInfo .. :: RedirectStandardOutput爲true。否則,從standardOutput流讀取拋出一個異常

你需要改變你的代碼一點點調整的變化:

Process myApp = new Process(@"C:\some\dirs\foo.exe", "someargs"); 
myApp.StartInfo.UseShellExecute = false; 
myApp.StartInfo.RedirectStandardOutput = false; 

myApp.Start(); 

string output = myApp.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 
+0

這很快...很抱歉沒有先嚐試TFM :(下次會做得更好 – 2009-11-09 12:34:47

0

如前所述上面,您可以使用RedirectStandardOutput作爲here

另外,骯髒的方式是一樣的東西

using (Process child = Process.Start 
    ("cmd", @"/c C:\some\dirs\foo.exe someargs > somefilename")) 
    { 
    exeProcess.WaitForExit(); 
    } 

然後從somefilename讀取其輸出