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

F.P*_*F.P 1 c# executable redirect console-application

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

我有一个我无法编辑的可执行文件,也没有看到它的代码.它在执行时将一些(相当多的是诚实的)行写入控制台.

现在我想编写另一个可执行文件来启动上面的那个并读取它写的东西.

对我来说似乎很简单,所以我开始编码,但结果却出现了一条错误消息 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();
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?!

Kas*_*dum 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();
Run Code Online (Sandbox Code Playgroud)