Process.Start()传递给Stdout

时间:2013-06-03 20:27:37

标签: c# process stdout

我想启动一个进程并读取标准输出,但也会在生成进程的控制台窗口中显示此读取输出。目前使用process.StartInfo.RedirectStandardOutput = true;BeginOutputReadLine()结合使得输出不会显示在控制台窗口中。这是不可取的。有谁知道怎么做或者甚至可能吗?

澄清评论。

我有一个响应进程输出的函数,我设置为:

    ProcessHandle.OutputDataReceived += new DataReceivedEventHandler(ProcessHandle_OutputDataReceived);

    void ProcessHandle_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
         ... //React to output here.
    }

但是这样做的输出没有进入生成进程的控制台窗口,有没有办法手动将它反馈到该控制台,所以它显示为好像我的应用程序没有截获它?

1 个答案:

答案 0 :(得分:0)

        var pi = new ProcessStartInfo
        {
            FileName = prog,
            Arguments = args,
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = false
        };

        var proc = new Process { StartInfo = pi };
        try
        {
            if (!proc.Start())
            {
                throw new ApplicationException("Starting proc failed!");
            }

            Console.WriteLine(proc.StandardOutput.ReadToEnd());
            proc.WaitForExit();
            if (proc.ExitCode != 0)
            {
                //throw new ApplicationException(String.Format("proc returned exit code {0}", proc.ExitCode));
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Unknown problem in proc", ex);
        }
        finally
        {
            if (!proc.HasExited)
                proc.Kill();
        }