RedirectStandardOutput eliminates the need for output files. It allows us to use a console program directly inside a C# program—without having to rely on output files being written to the disk. We redirect into a StreamReader.

Example

First, this program shows the use of the ProcessStartInfo class and its properties FileName, UseShellExecute and RedirectStandardOutput. It sets up the Process instance for having its output read in the C# program.

Next:The Process.Start method is run and the StandardOutput property on the Process instance is accessed and read from.

Note:This provides a way to redirect the output of a command line executable to the C# program as a string.

ProcessStartInfo is a settings class. It is attached to Process class to change the behavior of the Process invocation. To redirect the output of a process, set UseShellExecute to false and RedirectStandardOutput to true.

Also:You must specify the file name (with the FileName property) before calling Process.Start.

The using-statement is a safe way to use the Process and StreamReader classes. StreamReader is assigned to the StandardOutput stream on the process instance. We can then use ReadToEnd on the StreamReader to access the process text.

Tip:The ReadLine method can also be used on the StreamReader. This may be more efficient for larger amounts of data.

Process.Start

The Process class is available by including the using System.Diagnostics directive. This class interacts with the Windows OS. With it you can invoke any executable on the system. The system must be configured to allow this.

Summary

We used ProcessStartInfo to redirect the standard output of a command line executable to the C# program as a string. This provides a way to use a console program directly inside of a C# application. This avoids text files and pipes.