8.8. Capturing Standard Output for a Process

Problem

You need to be able to capture standard output for a process you are launching.

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 process, youread 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 program, 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 log file 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 standard output so we can read it.
	    application.StartInfo.RedirectStandardOutput = true; application.StartInfo.UseShellExecute ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.