我有一个 C# 应用程序 A
,它调用另一个 C# 应用程序 B
,后者又调用应用程序 C
的多个实例。
我想将应用程序 C 的输出重定向到应用程序 A 的输出。
我已经将应用程序 B
的输出重定向到应用程序 A
的输出。
现在,在应用程序 B 的代码中,我正在重定向每个进程的输出,并将重定向的输出打印到控制台。不幸的是,由于某种原因,没有打印任何内容。
(我目前正在测试它,而不使用应用程序 A
- 我只运行应用程序 B
)。
这是代码:
private void runSingleFile (string execFile, string commandArgs)
{
Process processToRun = new Process();
processToRun .StartInfo.FileName = execFile;
processToRun .StartInfo.Arguments = commandArgs;
processToRun .StartInfo.UseShellExecute = false;
processToRun .StartInfo.RedirectStandardOutput = true;
processToRun .OutputDataReceived += outputRedirection;
processToRun.Start();
Console.WriteLine("");
Thread.Sleep(100);
processToRun.BeginOutputReadLine();
}
private void outputRedirection(object sendingProcess, DataReceivedEventArgs outLine)
{
try
{
if (outLine.Data != null)
Console.WriteLine(outLine.Data);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
有什么想法吗?
最佳答案
.net Process
对象并不能让人们轻松地在正确处理 IO 方面“做正确的事情”。
这些页面列出了一些需要处理的问题:
- MSDN 的 ProcessStartInfo.RedirectStandardOutput Property页
- 雷蒙德的博客 Be careful when redirecting both a process's stdin and stdout to pipes...
- C# test.net 的 How to use System.Diagnostics.Process correctly
从您的代码示例中,以下是您需要查看的一些项目:
- 您需要捕获 stderr 和 stdin(后者如果不使用应立即关闭)。
- 您还需要注意,在子进程退出后,您仍然可以在
outputRedirection
回调上接收事件。
关于c# - 重定向标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20887266/