
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
476
|
Chapter 8: Diagnostics
Solution
Use the RedirectStandardOutput property of the Process.StartInfo class to capture
the output from the process. By redirecting the standard output stream of the pro-
cess, you read it when the process terminates.
UseShellExecute is a property on the
ProcessInfo class that tells the runtime whether or not to use the Windows shell to
start the process or not. By default, it is turned on (
true) and the shell runs the pro-
gram, which means that the output cannot be redirected. This needs to be set to off
and then the redirection can occur. The
UseShellExecute property is set to false to
ensure this is not started using the Windows shell for your purposes here.
In this example, a
Process object for cmd.exe is set up with arguments to perform a
directory listing, and then the output is redirected. A logfile is created to hold the
resulting output and the
Process.Start method is called.
// See 12.21 for more info on redirection...
Process application = new Process( );
// Run the command shell.
application.StartInfo.FileName = @"cmd.exe";
// Get a directory listing from the current directory.
application.StartInfo.Arguments = @"/Cdir " + Environment.CurrentDirectory;
Console.WriteLine("Running cmd.exe with arguments: {0}",
application.StartInfo.Arguments);
// Redirect ...