【问题标题】:Getting output from one executable in an other one从一个可执行文件中获取另一个可执行文件的输出
【发布时间】:2010-12-14 14:45:52
【问题描述】:

我目前正在尝试将可执行控制台应用程序的输出转换为另一个。确切地说,是对我正在尝试做的事情的一些概述:

我有一个无法编辑的可执行文件,也看不到它的代码。它在执行时会在控制台中写入一些(老实说相当多的)行。

现在我想编写另一个可执行文件来启动上面的那个并读取它写入的内容。

对我来说似乎很简单,所以我开始编码,但最终收到一条错误消息,指出 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();

我可以打开可执行文件,它也可以打开里面的那个,但是一旦读取返回值,应用程序就会崩溃。

我做错了什么?!

【问题讨论】:

标签: c# redirect executable console-application


【解决方案1】:

如上所述,您可以将 RedirectStandardOutput 用作 here

另一种更脏的方式是

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

然后从 somefilename

读取它的输出

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 那很快...抱歉没有先尝试 TFM :( 下次会做得更好
    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 2018-11-04
      • 2017-06-08
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多