2009-11-09 48 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读取其输出

相关问题