Click here to Skip to main content
Click here to Skip to main content

Redirecting external Process output to Console.Writeline (or elsewhere)

By , 22 Jun 2012
 

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Gilly Barr
Web Developer
Israel Israel
Started programming e-commerce sites with PHP & MySQL at the age of 14. Worked for me well for about 5 years.
 
Transfered to C# & asp.net, while serving in the IDF.
 
Currently working as a web developer for Sears Israel (SHC).
 
Check out my blog!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130619.1 | Last Updated 22 Jun 2012
Article Copyright 2012 by Gilly Barr
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid