运行 使用 C# 的 exe 文件时清空标准输出

Empty standard output when run an exe file using C#

我的问题可能看起来很直截了当,因为它被问了很多次before.Anyway我认为我的情况完全不同,我找不到任何关于它的直觉。我有一个用汇编语言编写的代码编译的 exe 文件,我想 运行 这个 exe 使用另一个代码并捕获它的输出。我使用 C# 完成了此操作,这是它的代码:

static string runCommand(string command, string args)
    {
        if (File.Exists(command))
        {
            Process p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.Arguments = args;
            p.Start();
            p.WaitForExit();
            string output = p.StandardOutput.ReadToEnd();
            return output; 
        }
        return "";
    }

目标exe文件的代码非常简单(我使用的是Irvine库):

INCLUDE Irvine32.inc


.data

.code
main proc
    call dumpregs
    exit
main ENDP

end main

其中command是exe文件路径,args是传递给exe文件的参数(注意不需要参数这个exe)

输出总是等于“”!。当我 运行 使用命令提示符的 exe 时,控制台输出绝对不是 empty.Here 我得到的是:

我也尝试使用 python 捕获控制台输出,但返回的字符串完全是空的。

我已经这样做了好几次了,但是 exe 文件是用 C# 而不是汇编语言编写的,但我认为应该没有任何区别存在。

编辑

目前已尝试并由 hatchet 建议的解决方案:

  1. 从 .NET 应用程序捕获控制台输出 (C#)
  2. 如何在 .NET 中生成进程并捕获其 STDOUT? [复制]
  3. Process.start:如何获取输出?

None 他们为我工作

如果您需要任何进一步的信息,请在评论中告诉我

您的 C# 代码是正确的。捕获控制台进程输出的标准方法是通过将进程对象的 StartInfo.RedirectStandardOutput 属性 设置为 true 来重定向标准输出,如 here 所述。这正是您所做的。

问题,如, is that you're using the Irvine32 library in the auxiliary process, and its implementation of dumpregs calls the Win32 WriteConsole function, which cannot be redirected. If you attempt to redirect the standard output (e.g., to a pipe or file), then WriteConsole will fail with ERROR_INVALID_HANDLE, as documented on MSDN:

ReadConsole and WriteConsole can only be used with console handles; ReadFile and WriteFile can be used with other handles (such as files or pipes). ReadConsole and WriteConsole fail if used with a standard handle that has been redirected and is no longer a console handle.

就像 rkhb 的评论一样,除了文档之外,这也暗示了解决方案。要支持重定向,您需要更改 dumpregs 的实现以调用 WriteFile 而不是 WriteConsole。这是一个更通用的函数,可以写入 any 类型的句柄,包括标准控制台输出 (a la WriteConsole) 您可能将输出重定向到的任何其他类型的对象。完成此更改后,您当然需要重建 Irvine32 库。

WriteFile 的唯一重大限制是它不像 WriteConsole 那样支持 Unicode 输出,但这在您的情况下不是问题。 dumpregs的输出都是ANSI。