ProcessInfo and RedirectStandardOutput

前端 未结 6 1140
無奈伤痛
無奈伤痛 2020-11-27 16:54

I have an app which calls another process in a command window and that process has updating stats that output to the console window. I thought this was a fairly simple opera

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 17:14

    I'm not sure exactly what problem you're running into, but if you're looking to act on output as soon as it's generated, try hooking into the process's OutputDataReceived event. You can specify handlers to receive output asynchronously from the process. I've used this approach successfully.

    Process p = new Process();
    ProcessStartInfo info = p.info;
    info.UseShellExecute = false;
    info.RedirectStandardOutput = true;
    info.RedirectStandardError = true;
    
    p.OutputDataReceived += p_OutputDataReceived;
    p.ErrorDataReceived += p_ErrorDataReceived;
    
    p.Start();
    
    p.BeginOutputReadLine();
    p.BeginErrorReadLine();
    p.WaitForExit();
    

    ..

    void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
      Console.WriteLine("Received from standard out: " + e.Data);
    }
    
    void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
      Console.WriteLine("Received from standard error: " + e.Data);
    }
    

    See the OutputDataReceived event off Process for more information.

提交回复
热议问题