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

前端 未结 3 1953
青春惊慌失措
青春惊慌失措 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: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
                }
            }
    

提交回复
热议问题