Making Command Line Calls In .NET

Sometimes you just need to call a console executable.  Whether it is legacy code or the only interface for 3rd party software, console applications are still used and still need to be interfaced with.  Fortunately, .NET comes with a class built specifically to get that job done.  The Process class, located in the Systems.Diagnostics library, can be called to handle console executables and their command line arguments.  Below is an example on how to call this useful class:

Process proc = new Process();

// First, specify the executable file name and any command line arguments
proc.StartInfo = new ProcessStartInfo("C:\\temp\\CmdLineProgram.exe", 
     "-i \"C:\\temp\\InputFile.txt\" -o \"C:\\temp\\OutputFile.txt\"");

// Next, since we want to run this in our program, we don't want the 
// shell to execute it nor have it display in an external window.
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;

// We also want to get any error or output data that the executable might write out.
// This should capture data normally written out to the console screen.
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;

// Now let the executable run.  We'll wait here for it to finish process.
proc.Start();
proc.WaitForExit();

// Gather any exit code information
int exitCode = proc.ExitCode;

// And get the output and error messages.
string errorMsg = string.Empty;
using (StreamReader reader = proc.StandardError)
{
     errorMsg = reader.ReadToEnd();
}string outMsg = string.Empty;
using (StreamReader reader = proc.StandardOutput)
{
     outMsg = reader.ReadToEnd();
}

Hopefully this small sample will help out with making calls to console applications.  Regarding retrieval of exit codes, output and error messages, not all console applications like to output them to the same place.  Sometimes all output messages actually go to the error message, so you may need to look there.  Some trial and error may be necessary, so make sure to test out the code to find what works and what doesn’t.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s