在C#中读取控制台命令输出时出现“StandardOut未被重定向或进程尚未启动”的错误提示。

33

感谢@user2526830提供的代码。基于那段代码,我在我的程序中添加了一些行,因为我想读取SSH命令的输出。以下是我的代码,在while行处出现错误。

StandardOut未被重定向或进程尚未启动。

我的目标是将ls的输出读入字符串中。

ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = @"f:\plink.exe";
startinfo.Arguments = "-ssh abc@x.x.x.x -pw abc123";
Process process = new Process();
process.StartInfo = startinfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.StandardInput.WriteLine("ls -ltr /opt/*.tmp");
process.StandardInput.WriteLine("exit");

process.StartInfo.RedirectStandardOutput = true;

while (!process.StandardOutput.EndOfStream)
{
    string line = process.StandardOutput.ReadLine();
}

process.WaitForExit();
Console.ReadKey();
2个回答

57

在启动进程之前尝试设置标准输出重定向。

process.StartInfo.RedirectStandardOutput = true;
process.Start();

8

当您尝试读取输出时,可能是处理过程已经终止(由于您的"exit"命令)。请尝试下面稍作修改的版本,在"ls"命令之后但在"exit"命令之前移动您的while循环。

它应该可以正确读取您的"ls"命令的输出,但不幸的是,由于永远无法获得StandardOutput的EndOfStream,它很可能会在某个时刻挂起。当没有更多内容可读取时,ReadLine将阻塞,直到可以获取另一行。

因此,除非您知道如何检测命令生成的输出的最后一行并在读取完毕后退出循环,否则您可能需要使用单独的线程进行读取或写入。

ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = @"f:\plink.exe";
startinfo.Arguments = "-ssh abc@x.x.x.x -pw abc123";
Process process = new Process();
process.StartInfo = startinfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
process.StandardInput.WriteLine("ls -ltr /opt/*.tmp");

while (!process.StandardOutput.EndOfStream)
{
    string line = process.StandardOutput.ReadLine();
}

process.StandardInput.WriteLine("exit");
process.WaitForExit();
Console.ReadKey();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接