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

标签 c# redirect executable 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();

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

我究竟做错了什么?!

最佳答案

查看 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/

相关文章:

c# - PersianCalendar 无法将年/月/31(日)转换为标准日期

c# - 使用 AAD 对 Azure API 应用程序进行身份验证时出现 401 错误

c# - lambda 表达式使用反射吗?

bash - "2>&1 "是什么意思?

python - 在 PyInstaller 中打包多个脚本

python - 使用 chromedriver 和 Selenium 创建 Python 可执行文件

c# - .Net Core 项目中 vs2017 缺少 web.config

redirect - 如何在没有 html header 的情况下将 nginx 重定向到非 http

.htaccess - 强制域通过 HTTPS 加载

java - 部署 Maven one-jar 会部署错误的 Artifact