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

WoodyStory picture WoodyStory · Jun 8, 2016 · Viewed 23.2k times · Source

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();

Answer

Oscar picture Oscar · Jun 8, 2016

Try setting standard output redirection before starting the process.

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