I have a form with textBox output_txtB and I want to run cmd, execute some commands and display standard output in the textbox. I want to retrieve standard output after execute each command, while child process is working. I've found some solutions here:
Redirect the output (stdout, stderr) of a child process to the Output window in Visual Studio
C# get process output while running
But it didn't solve my specific problem, because I want to display standard output in the textbox (not in the console or elsewhere) and do it immediately after execute each command - I don't want to retrieve full output after process exit.
I've tried to use OutputDataReceived event in the child process, as suggested in above links, but there is a problem, when I want to refer to the textbox, which was created on another thread - it throws an InvalidOperationException. Here is my code:
Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo.FileName = "cmd";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.OutputDataReceived += (sender, args) =>
{
//here throws an exception
output_txtB.AppendText(args.Data + Environment.NewLine);
};
process.Start();
process.BeginOutputReadLine();
//commands I want to execute
process.StandardInput.WriteLine("example.exe");
process.StandardInput.WriteLine("script.bat");
process.StandardInput.WriteLine("ipconfig /all");
process.StandardInput.WriteLine("dir");
process.StandardInput.Close();
process.WaitForExit();
Additional information of the exception is:
Cross-thread operation not valid: Control 'output_txtB' accessed from a thread other than the thread it was created on.
Any ideas, how to retrieve standard output of the child process, and display it in the textbox, while child process is working?
EDIT: See "example.exe" code:
Console.WriteLine("line 1");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("line 2");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("line 3");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("line 4");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("line 5");
What I'm trying to achieve, is to display in the textbox line X each time, the process receives it in the standard output. But even if I use Stefano's solution, it seems like OutputDataReceived event fires and displays full process output after process exit.