gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:19:01 31 4
gpt4 key购买 nike

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

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

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

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

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

我究竟做错了什么?!

最佳答案

查看 Process.StandardOutput 的文档属性(property)。您将需要设置一个 bool 值,指示您希望流重定向以及禁用 shell 执行。

文档中的注释:

To use StandardOutput, you must set ProcessStartInfo..::.UseShellExecute to false, and you must set ProcessStartInfo..::.RedirectStandardOutput to true. Otherwise, reading from the StandardOutput stream throws an exception



您需要稍微更改代码以适应更改:
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();

关于c# - 从一个可执行文件中获取另一个可执行文件的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1700695/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com