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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 04:38:30

问题


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


回答1:


By redirecting it and reading the stream.




回答2:


To solve the deadlock problems use this approach:

ProcessStartInfo hanging on "WaitForExit"? Why?

Works well in my code...




回答3:


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
            }
        }


来源:https://stackoverflow.com/questions/3633653/how-to-capture-the-standard-output-error-of-a-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!