捕获的输出为空

本文关键字:输出 | 更新日期: 2023-09-27 18:13:07

我试图捕获来自其他应用程序的输出。捕获ping的输出效果很好。变量output包含预期的输出。

    var p = new Process();
    p.StartInfo.FileName = "ping";
    p.StartInfo.Arguments = "www.google.com";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();
    var output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

但是,当我使用这段代码捕获expdp(这是一个用于导出的oracle工具)的输出时,变量为空。在控制台中运行相同的命令将返回一些输出。

    p.StartInfo.FileName = "expdp";
    p.StartInfo.Arguments = "help=y";

捕获的输出为空

尝试检查StandardError流,看看是否有任何内容

var p = new Process();
p.StartInfo.FileName = "expdp";
p.StartInfo.Arguments = "help=y";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
var error = p.StandardError.ReadToEnd();
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

有一点需要注意,如果输出流或错误流太长,那么这种方法可能会导致死锁。

如果是这种情况,您将不得不异步读取其中一个流。

我曾经遇到过这个问题。最近的答案确实有道理,但我还没有测试过,因为它是在我遇到问题6个月后出现的。基本上,问题似乎是ReadToEnd()在一个精确的时刻读取,就在p.Start()之后,还没有任何内容输出到屏幕上。您可以通过在开始和ReadToEnd()之间设置一个长睡眠来检查它。