Share via


Redirecting Standard Error & Output For A Child Process

If your application or library wants to kick off a child process C and you want to redirect standard output and error, this is what you do:

ProcessStartInfo psi = new ProcessStartInfo();

          
            psi.Arguments = this.CreateArgumentsString();
             psi.FileName = this.ImageFile;
            psi.CreateNoWindow = true;
            psi.RedirectStandardError = true;
             psi.RedirectStandardInput = true;
             psi.RedirectStandardOutput = true;
            psi.WorkingDirectory = this.WorkingDirectory;
             psi.UseShellExecute = false;
             
            Process p = new Process();
          
            p.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputDataReceived);
             p.ErrorDataReceived += new DataReceivedEventHandler(ProcessErrorDataReceived);
           p.StartInfo = psi;
          p.EnableRaisingEvents = true;

p.Start();

p.BeginErrorReadLine();

             p.BeginOutputReadLine();
          p.WaitForExit();
  
 That will redirect output and error data from your child process to the console asynchronously (er, depending on the implementation of ProcessOutputDataReceived and ProcessErrorDataReceived). Which is good because if the invoking application is a console application and you want to see the output/error in real time then you want it to work like this.