As part of some code I was writing recently, At some point my app needed to trigger some other command line utility. I did this easily, using the Process class like this :
var myProcess = new Process {
StartInfo = {
FileName = "C:\\path\\to\\my\\cmd\\utility.exe",
Arguments = " --some --random --args"
}
};
myProcess.Start();
This was working great, with one exception - Sometimes the process was throwing an error, causing the console window to close immediately, and I didn't have time to view this error.
I knew that you can tell there was an error by the process's exit code (myProcess.ExitCode), but while debugging it was important to know what error
was happening and actually see the output of this process.
Digging a little into the Process class, I easily found that you can redirect the process's output elsewhere. You just need to add :
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
myProcess.Start();
myProcess.BeginOutputReadLine();
That's it! Now i was getting all I needed from the running process, and it was much easier to find the problem this way. Enjoy!