Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process RedirectStandardOutput empty and DataReceivedEventArgs.Data is null

When running an application in console mode there are lines written to the console.

Now I want to do this programmatically. Here is some example code that I used: MSDN on OutputDataReceived Event

private static StringBuilder _sortOutput = null;

var proc = new Process();
                var info = new ProcessStartInfo();
            info.FileName = @"C:\SomeApp.exe";

            info.UseShellExecute = false;
            info.WindowStyle = ProcessWindowStyle.Normal;
            info.CreateNoWindow = false;

            proc.StartInfo = info;

            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;

            proc.OutputDataReceived += HandleOutputData;
            proc.ErrorDataReceived += HandleOutputData;

            proc.Start();
            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();

            proc.WaitForExit();

            var exitCode = proc.ExitCode;
            var output = _sortOutput.ToString();


    private void HandleOutputData(object sender, DataReceivedEventArgs e)
    {
        _sortOutput.Append(e.Data);
    }

But the DataReceivedEventArgs.Data is always null and I do not get back the result which I can see in the console window that opens.

How can I receive the output? Is there a way to achieve that?

UPDATE

I also tried to read the proc.StandardOutput directly, but it does not yield any data.

like image 636
Mare Infinitus Avatar asked Mar 03 '26 03:03

Mare Infinitus


1 Answers

As someone else has spotted, there is a bug where _sortOutput will be null. But regardless of that, you are completely correct: e.Data can and will be null!

In fact, your handler should always get called with e.Data equal to null when the AsyncStreamReader that is doing the calling reaches EOF of the standard output that is being redirected - which will happen when the process you are running exits. Unless, of course, you deregister your OutputDataReceived event handler first, or cancel asynchronous output redirection.

like image 128
Tim Lovell-Smith Avatar answered Mar 04 '26 21:03

Tim Lovell-Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!