Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Thanks to @user2526830 for the code. Based on that code I added few lines to my program since I want to read the output of the SSH command. Below is my code which gives an error at line while

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

What I want to achieve is that I want to read the output of ls into a string.

ProcessStartInfo startinfo = new ProcessStartInfo(); startinfo.FileName = @"f:\plink.exe"; startinfo.Arguments = "-ssh [email protected] -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(); 
like image 488
WoodyStory Avatar asked Jun 08 '16 06:06

WoodyStory


2 Answers

Try setting standard output redirection before starting the process.

process.StartInfo.RedirectStandardOutput = true; process.Start(); 
like image 77
Oscar Avatar answered Sep 30 '22 14:09

Oscar


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.

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. When there is nothing more to read, ReadLine will block until it can get read another line.

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 [email protected] -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(); 
like image 41
Maciej Grzyb Avatar answered Sep 30 '22 15:09

Maciej Grzyb