Search code examples
c#.nettee

Redirect a process's output to both a file and the console


I need to execute a shell command from c# code and then log to a file the output of the shell.

The code i use to execute the shell command is:

using (var process = Process.Start(new ProcessStartInfo
{
    FileName = fileName,
    Arguments = arguments,
    CreateNoWindow = false,
    WindowStyle = ProcessWindowStyle.Normal,
    RedirectStandardOutput = false,
    UseShellExecute = true,
}))
{
    // blocking wait for the process to end
    process.WaitForExit();
}

I read other answers that change RedirectStandardOutput = true and useShellExecute = false so they can get console output with

string output = process.StandardOutput.ReadToEnd();

But this won't open the shell window.

Is there a way to display the command output to the console window and get that output?


Solution

  • Could use something like that

    using System;
    using System.Diagnostics;
    
        namespace InteractWithConsoleApp
        {
            class Program
            {
                static void Main(string[] args)
                {
                    ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
                    cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                    cmdStartInfo.RedirectStandardOutput = true;
                    cmdStartInfo.RedirectStandardError = true;
                    cmdStartInfo.RedirectStandardInput = true;
                    cmdStartInfo.UseShellExecute = false;
                    cmdStartInfo.CreateNoWindow = true;
    
                    Process cmdProcess = new Process();
                    cmdProcess.StartInfo = cmdStartInfo;
                    cmdProcess.ErrorDataReceived += cmd_Error;
                    cmdProcess.OutputDataReceived += cmd_DataReceived;
                    cmdProcess.EnableRaisingEvents = true;
                    cmdProcess.Start();
                    cmdProcess.BeginOutputReadLine();
                    cmdProcess.BeginErrorReadLine();
    
                    cmdProcess.StandardInput.WriteLine("ping google.com.ua");     //Execute ping google.com.ua
                    cmdProcess.StandardInput.WriteLine("exit");                  //Execute exit.
    
                    cmdProcess.WaitForExit();
                }
    
                static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
                {
                    Console.WriteLine("Output from other process");
                    Console.WriteLine(e.Data);
                }
    
                static void cmd_Error(object sender, DataReceivedEventArgs e)
                {
                    Console.WriteLine("Error from other process");
                    Console.WriteLine(e.Data);
                }
            }
        }