Capturing process output via OutputDataReceived event

后端 未结 2 1589
野趣味
野趣味 2020-12-01 13:48

I\'m trying to capture process output in \"realtime\" (while it\'s running). The code I use is rather simple (see below). For some strange reason the OutputDataReceived even

相关标签:
2条回答
  • void ExecuteCommand(string cmdpath, string cmdargs)
    {
        string command = cmdpath + " " + cmdargs;
    
        tabc_results.SelectTab(1); 
        DoConsole("\r\nCmd>> " + command + "\r\n");
    
        var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);
        processInfo.CreateNoWindow = true;
        processInfo.UseShellExecute = false;
        processInfo.RedirectStandardError = true;
        processInfo.RedirectStandardOutput = true;
    
        var process = System.Diagnostics.Process.Start(processInfo);
    
        process.OutputDataReceived += (
            object sender, System.Diagnostics.DataReceivedEventArgs e
        ) => DoConsole("stdout>>  " + e.Data + "\r\n");
        //Console.WriteLine("output>>" + e.Data);
        process.BeginOutputReadLine();
    
        process.ErrorDataReceived += (
            object sender, System.Diagnostics.DataReceivedEventArgs e
        ) =>DoConsole("stderr>>  " + e.Data + "\r\n");
        //Console.WriteLine("error>>" + e.Data);
        process.BeginErrorReadLine();
    
        process.WaitForExit();
    
        DoConsole("retcode>> " + process.ExitCode.ToString() + "\r\n");
        //Console.WriteLine("ExitCode: {0}", process.ExitCode);
        process.Close();
    }
    
    0 讨论(0)
  • 2020-12-01 14:21

    You need to call

    mProcess.BeginOutputReadLine();
    

    BeginOutputReadLine - "Begins asynchronous read operations on the redirected StandardOutput stream of the application."

    0 讨论(0)
提交回复
热议问题