articles

Home / DeveloperSection / Articles / RedirectStandardOutput properties in C#

RedirectStandardOutput properties in C#

Anonymous User5852 25-Aug-2011

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

usingSystem.Diagnostics;
usingSystem.Threading;
usingSystem.IO;
namespaceConsoleProcessTest
{
    classProgram
    {
        staticvoidMain(string[] args)
        {
 
            ProcessStartInfomyStart= 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
            ProcessmyProcess= Process.Start(myStart);
            // read all text from process stream reader
                stringmessage= myProcess.StandardOutput.ReadToEnd();
            // write the message on console
                Console.WriteLine(message);
                Console.ReadKey();
        }
      
    } 
  
}
Output:

RedirectStandardOutput properties in C#

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



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By