我通过 Process 类启动一个 exe,我注意到 exe 的输出显示在我的应用程序的命令窗口中。 *注意 - 当我启动 exe 时,我确保没有打开窗口 - 因此,应用程序运行时显示的唯一窗口是我的主应用程序 project.exe。
有没有办法阻止 exe 的输出显示在我的 project.exe 命令窗口中?这是我的代码:
Process process = new Process();
string exePath = System.IO.Path.Combine(workingDir, exeString);
process.StartInfo.FileName = exePath;
process.StartInfo.WorkingDirectory = workingDir;
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (s, e) => Logger.LogInfo(e.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
我什至尝试将 RedirectStandardOutput 设置为 false:
process.StartInfo.RedirectStandardOutput = false;
并且输出仍然放置在命令窗口中。
当我在我的盒子上本地尝试时,这是有效的。你可以通过替换exe路径/名称来尝试一下吗?
来自 MSDN 文档。
“当进程将文本写入其标准流时,该文本通常会显示在控制台上。通过将 RedirectStandardOutput 设置为 true 来重定向 StandardOutput 流,您可以操纵或抑制进程的输出。例如,您可以过滤文本,以不同的方式格式化它,或者将输出写入控制台和指定的日志文件”
void Main()
{
Process process = new Process();
string exePath = System.IO.Path.Combine(@"C:\SourceCode\CS\DsSmokeTest\bin\Debug", "DsSmokeTest.exe");
process.StartInfo.FileName = exePath;
process.StartInfo.WorkingDirectory = @"C:\SourceCode\CS\DsSmokeTest\bin\Debug";
process.StartInfo.Arguments = string.Empty;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (s, e) => Test(e.Data);
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
// Define other methods and classes here
public void Test(string input)
{
input.Dump();
}
在 .Net 8 上,我所要做的就是添加
process.StartInfo.RedirectStandardOutput = true;
并且输出未显示在我的应用程序的控制台上
完整代码:
Process process = new()
process.StartInfo.FileName = appPath;
process.StartInfo.Arguments = command;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
只需添加以下行
process.StartInfo.UseShellExecute = true;