I'm building a small Console Application that sometimes will use the Windows Command Line, to send a command and then receive and display the output.
Opening a new Command Line instance was easy, sending commands from my Application took a bit of digging but its working. However i can't seem to be able to read the output from the Command Line.
My code is based on:
How to redirect Standard Input/Output of an application
How do I run Command line commands from code
I applied the same way of reading the output to my application, and it doesn't work, not until the moment i close my application, while is being shutdown I'm able to have a glimpse at the output.
Its working, but most likely i have misplaced code, that prevents me to see the output, until i start to shutdown my application.
Can somebody help me with this?
Code:
Process p = new Process();
p.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec");
p.StartInfo.ErrorDialog = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
//Execute the process
if (p.Start())
{
//Get the output stream
StreamReader outputReader = p.StandardOutput;
StreamReader errorReader = p.StandardError;
// Assign a Stream Writer to send the Commands
StreamWriter commandWriter = p.StandardInput;
// Send the "Dir" command to the command line instance.
commandWriter.Write("dir");
commandWriter.Write(commandWriter.NewLine);
p.WaitForExit();
//Display the result
Console.WriteLine(outputReader.ReadToEnd());
outputReader.Close();
errorReader.Close();
commandWriter.Close();
}