How to capture the standard output/error of a Process?

前端 未结 3 1955
青春惊慌失措
青春惊慌失措 2021-01-20 01:46

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

相关标签:
3条回答
  • 2021-01-20 02:23

    To solve the deadlock problems use this approach:

    ProcessStartInfo hanging on "WaitForExit"? Why?

    Works well in my code...

    0 讨论(0)
  • 2021-01-20 02:25

    By redirecting it and reading the stream.

    0 讨论(0)
  • 2021-01-20 02:29

    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
                }
            }
    
    0 讨论(0)
提交回复
热议问题