1

Lots of answers to other questions tell you that you can capture the output of a process using code looking something like this:

public async Task Run()
{
    await Task.Run(() =>
    {
        using (Process process = new Process()
        {
            StartInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                FileName = "cmd",
                Arguments = "path/filename.bat",
            }
        })
        {
            process.OutputDataReceived += Process_OutputDataReceived;
            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();
        }
    });
}

private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        log.Error(e.Data);
    }
}

private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        log.Info(e.Data);
    }
}

There are lots of variants which achieve the same thing more or less but they all redirect the standard output/errors - is there a way to capture them while still having them show in the cmd window?

11
  • Why do you need to show the output from the original terminal if your program is redirecting it? Can you just create a control on your program that displays the child process' output, or even create your own console window if you want it to look the same? Commented Apr 15, 2019 at 23:12
  • I marked this as a duplicate, but please let me know if the duplicate does not resolve your question (and update your question with the specifics of what else you want). Commented Apr 15, 2019 at 23:19
  • The trick is to do something like var output = p.StandardOutput.ReadToEnd(); before calling process.WaitForExit(); Commented Apr 15, 2019 at 23:20
  • @RufusL - that question does not appear to answer my question. They are asking about reading a process's output in real-time rather than having to wait for the process to end, like the code in my question already does. I am asking about reading the process's output while not removing it from the console window. Commented Apr 15, 2019 at 23:26
  • 1
    There is no "splitter" for streams. If you want one, you'll have to create one. For example, you could add calls to Console.Error.Write and Console.Write to Process_ErrortDataReceived. and `Process_OutputDataReceived. Commented Apr 16, 2019 at 0:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.