Suppose that we have a console application which is written in any language and we want to invoke it directly in our C# Programming, without having to rely on output files being written to the disk. The Process and ProcessStartInfo classes (available in System.Diagnostics namespace) in the C# language provide a way to redirect the standard output of a process executable to the C# program into a StreamReader and get it into C# string variable.
Example: RedirectStandardOutput of invoking console application in C# program
using System.Diagnostics;
using System.Threading;
using System.IO;
namespace ConsoleProcessTest
{
class Program
{
static voidMain(string[] args)
{
ProcessStartInfo myStart= new ProcessStartInfo();
//.exe path with exe file name
myStart.FileName= @"C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe";
//indicating whether to use the operating system shell to start the process
myStart.UseShellExecute= false;
// Enable the RedirectStandardOutput
myStart.RedirectStandardOutput= true;
// start process of processstartinfo
Process myProcess= Process.Start(myStart);
// read all text from process stream reader
string message= myProcess.StandardOutput.ReadToEnd();
// write the message on console
Console.WriteLine(message);
Console.ReadKey();
}
}
}
Output:

Note: When you use RedirectStandarOutput then you must be specify the filename.
Leave Comment