代码之家  ›  专栏  ›  技术社区  ›  F.P

从另一个可执行文件中的一个获取输出

  •  1
  • F.P  · 技术社区  · 15 年前

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

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

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

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

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

    我做错什么了?!

    3 回复  |  直到 15 年前
        1
  •  6
  •   Kasper Holdum    15 年前

    查看文档 Process.StandardOutput 财产。您需要设置一个布尔值,指示您希望流被重定向以及禁用shell执行。

    文档中的注释:

    若要使用StandardOutput,必须将ProcessStartInfo..::.UseShellExecute设置为false,并且必须将ProcessStartInfo..::.RedirectStandardOutput设置为true。否则,从标准输出流读取将引发异常

    您需要稍微更改代码以适应更改:

    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();
    
        2
  •  2
  •   brysseldorf    15 年前
        3
  •  0
  •   yu_sha    15 年前

    如上所述,您可以使用RedirectStandardOutput作为 here .

    另一个更脏的方法是

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

    然后从 SomeFileName文件名