Getting data from Process.StandardOutput on the fly

335 Views Asked by At

I am trying to get data from Process.StandardOutput ... but I have a problem : i get the data when the process is ended, but not during execution (does it not flush ???) . It looks like the data is bufferred somewhere. When I run the process manually the messages apper during execution. How to fix?

1

There are 1 best solutions below

2
On

this is what I use to grab output from a process. This is adding to a stringbuilder, but you could do other things.

    private void RunWithOutput(string exe, string parameters, out string result, out int exitCode)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo(exe, parameters);
        startInfo.CreateNoWindow = true;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardError = true;
        startInfo.RedirectStandardOutput = true;
        Process p = new Process();
        p.StartInfo = startInfo;

        p.Start();

        StringBuilder sb = new StringBuilder();
        object locker = new object();
        p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args) 
        {
            lock(locker)
            {
                sb.Append(args.Data);
            }
        } );
        p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs args)
        {
            lock (locker)
            {
                sb.Append(args.Data);
            }
        });

        p.BeginErrorReadLine();
        p.BeginOutputReadLine();

        p.WaitForExit();
        result = sb.ToString();
        exitCode = p.ExitCode;
    }