"StandardOut has not been redirected or the process hasn't started yet" 在 C# 中读取控制台命令输出时

"StandardOut has not been redirected or the process hasn't started yet" when reading console command output in C#

感谢@user2526830 提供代码。基于该代码,我在程序中添加了几行,因为我想读取 SSH 命令的输出。下面是我的代码,它在 while

行给出了错误

StandardOut has not been redirected or the process hasn't started yet.

我想实现的是把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();

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

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

可能是当您尝试读取输出时进程已经终止(由于您的 "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();