[英]“StandardOut has not been redirected or the process hasn't started yet” when reading console command output in C#
Thanks to @user2526830 for the code.感谢@user2526830 提供代码。 Based on that code I added few lines to my program since I want to read the output of the SSH command.
基于该代码,我在程序中添加了几行,因为我想读取 SSH 命令的输出。 Below is my code which gives an error at line
while
下面是我的代码,在行给出了一个错误
while
StandardOut has not been redirected or the process hasn't started yet.
StandardOut 尚未重定向或进程尚未启动。
What I want to achieve is that I want to read the output of ls into a string.我想要实现的是我想将 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();
Try setting standard output redirection before starting the process.在开始该过程之前尝试设置标准输出重定向。
process.StartInfo.RedirectStandardOutput = true;
process.Start();
It might be that the process already terminated when you try to read the output (dues to your "exit" command).当您尝试读取输出(由于您的“退出”命令)时,该进程可能已经终止。 Try the below slightly modified version where I moved your while loop after the "ls" command but before the "exit" command.
试试下面稍微修改过的版本,我在“ls”命令之后但在“exit”命令之前移动了你的while循环。
It should read the output of your "ls" command fine, but unfortunately will most probably hang at some point as you will never get EndOfStream on the StandardOutput.它应该可以很好地读取“ls”命令的输出,但不幸的是,很可能会在某个时候挂起,因为您永远不会在 StandardOutput 上获得 EndOfStream。 When there is nothing more to read, ReadLine will block until it can get read another line.
当没有更多可读取时,ReadLine 将阻塞,直到它可以读取另一行。
So unless you know how to detect the last line of the output generated by your command and break out of the loop after you read it, you may need to use a separate thread either for reading or for writing.因此,除非您知道如何检测命令生成的输出的最后一行并在读取后跳出循环,否则您可能需要使用单独的线程进行读取或写入。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.