6

How does one capture the standard output/error of a process started by a Process.Start() to a string?

Servy
  • 202,030
  • 26
  • 332
  • 449
Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

3 Answers3

1

To solve the deadlock problems use this approach:

ProcessStartInfo hanging on "WaitForExit"? Why?

Works well in my code...

Community
  • 1
  • 1
SAL
  • 1,218
  • 1
  • 14
  • 34
0

By redirecting it and reading the stream.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 10
    -1: The linked article runs into a deadlock issue (at least, at the time of writing this): As stated by the MSDN Documentation: "A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream". – tstone2077 Sep 04 '14 at 20:03
-1

Sample code is below:

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.CreateNoWindow = false;
        psi.UseShellExecute = false;
        psi.FileName = "C:\\my.exe";
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        using (Process exeProcess = Process.Start(psi))
        {
            exeProcess.WaitForExit();

            var exitCode = exeProcess.ExitCode;
            var output = exeProcess.StandardOutput.ReadToEnd();
            var error = exeProcess.StandardError.ReadToEnd();

            if (output.Length > 0)
            {
                // you have some output
            }


            if(error.Length > 0)
            {
                // you have some error details
            }
        }
bev
  • 372
  • 3
  • 5
  • 1
    You need to set UseShellExecute to true for the Verb to be respected and it must be set to 'false' to redirect standard output. You can't do both. I'm pretty sure Windows also won't allow you to redirect standard input/output/error across the admin/non-admin security boundary. You'll have to find a different way to get output from the program running as admin - Reference: http://stackoverflow.com/a/8690661 – Kiquenet Aug 28 '14 at 06:35
  • 7
    -1. As stated by the MSDN Documentation: "A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream". Your code does exactly that. – tstone2077 Sep 04 '14 at 20:01