Pregunta

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.

¿Fue útil?

Solución 2

It's null, because you read the data in var outPut

Try following:

a) Change the way you handle it

proc.OutputDataReceived += new DataReceivedEventHandler(HandleOutputData);

b)Comment out the line

//var outPut = proc.StandardOutput.ReadToEnd();

Otros consejos

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.

Null signifies the end of the asynchronous stream. You must both WaitForExit and wait for the terminating null to come through e.Data

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top