StandardOutputEncoding 的唯一影响对执行的应用程序的标准输出没有任何影响。它所做的唯一事情是设置位于从正在运行的应用程序捕获的二进制标准输出流顶部的 StreamReader 的编码。
这对于本机输出 UTF8 或 Unicode 标准输出的应用程序来说是可以的,但大多数 Microsoft 实用程序都这样做not这样做,只会根据控制台的代码页对结果进行编码。控制台的代码页是使用 WIN32 API 手动设置的SetConsoleOutputCP
and SetConsoleCP
,并且如果您想阅读的话,需要手动强制为 UTF8。这需要在正在执行 exe 的控制台上完成,并且据我所知,无法从主机的 .NET 环境中完成。
因此,我编写了一个名为 UtfRedirect 的代理应用程序,我已经发布了其源代码在 GitHub 上 https://github.com/NeoSmart/UtfRedirect根据 MIT 许可证的条款,该许可证旨在在 .NET 主机中生成,然后告诉执行哪个 exe。它将为最终从属 exe 的控制台设置代码页,然后运行它并将标准输出通过管道传输回主机。
UtfRedirector 调用示例:
//At the time of creating the process:
_process = new Process
{
StartInfo =
{
FileName = application,
Arguments = arguments,
RedirectStandardInput = true,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
UseShellExecute = false,
},
};
_process.StartInfo.Arguments = "";
_process.StartInfo.FileName = "UtfRedirect.exe"
//At the time of running the process
_process.Start();
//Write the name of the final slave exe to the stdin of UtfRedirector in UTF8
var bytes = Encoding.UTF8.GetBytes(application);
_process.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
_process.StandardInput.WriteLine();
//Write the arguments to be sent to the final slave exe to the stdin of UtfRedirector in UTF8
bytes = Encoding.UTF8.GetBytes(arguments);
_process.StandardInput.BaseStream.Write(bytes, 0, bytes.Length);
_process.StandardInput.WriteLine();
//Read the output that has been proxied with a forced codepage of UTF8
string utf8Output = _process.StandardOutput.ReadToEnd();