Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Redirecting External Process Output to Console.Writeline (Or Elsewhere)

0.00/5 (No votes)
22 Jun 2012 1  
At some point, my app needed to trigger some other command line utility.

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:

// This needs to be set to false, in order to actually redirect the standard shell output
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;

// This is the event that is triggered when output data is received.
// I changed this to Console.WriteLine() - you can use whatever you want basically...
myProcess.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);

myProcess.Start();

myProcess.BeginOutputReadLine(); // without this, the OutputDataReceived event won't ever be triggered

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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here