0

I am using a Process to run the cmd.exe in C# (WinForms).

I am able to redirect the standard output (either by capturing the event or reading the StreamReader) to a .txt file:

private async Task ExecuteCommandAsync(string command)
{
    using var process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = command;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.OutputDataReceived += CommandPrompt_OutputReceived;

    // ...
}

and I'm able to write the output directly to the console window:

private async Task ExecuteCommandWithWindowAsync(string command)
{
    using var process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = command;
    process.StartInfo.CreateNoWindow = false;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

    // ...
}

But I can't find any way of doing both, i.e. write to the console window AND redirect the standard output to a .txt file.

Does anyone know if I'm missing something obvious? Or will I need to grab the string in a different way?

2
  • @shingo oh man, I thought I searched all the SO relevant questions. I feel I prize idiot. Thanks for the link. Commented Dec 6, 2023 at 10:49
  • WHy are you running cmd to run other commands, why don't you just run those commands directly? Commented Dec 6, 2023 at 13:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.