C
C#13mo ago
Dawid

❔ (WPF App) Show terminal window with all output, but also read it with code and catch errors.

Hi, I don't know how to show all the output in terminal window when RedirectStandardOutput and RedirectStandardError are enabled, so temporarily I hide it as it doesn't have any output anyway but is there a way for it to work? Below is my code. When showConsoleWindow is true, I want all output to be shown by terminal window and to be read by program to handle errors etc. (It's not the full code because discord doesn't allow that big message, but I think everything which is needed to understand my issue is here)
var startInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
RedirectStandardInput = true,
RedirectStandardOutput = !showConsoleWindow,
RedirectStandardError = !showConsoleWindow,
CreateNoWindow = !showConsoleWindow,
UseShellExecute = false,
Verb = "runas"
};

if (showConsoleWindow)
{
startInfo.WindowStyle =
ProcessWindowStyle.Normal;
}

var process = new Process { StartInfo = startInfo };
process.Start();

await process.StandardInput.WriteLineAsync(command);

if (showConsoleWindow)
{
var delayTask = Task.Delay(5000);
var exitTask = Task.Run(() => process.WaitForExit());
await Task.WhenAny(delayTask, exitTask);

if (!process.HasExited) process.CloseMainWindow();

return true;
}

process.StandardInput.Close();

await process.WaitForExitAsync();

var success = process.ExitCode == 0;
var error = await process.StandardError.ReadToEndAsync();

if (!success)
{
// Error message box
}
else
{
// Success message box
}

return success;
var startInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
RedirectStandardInput = true,
RedirectStandardOutput = !showConsoleWindow,
RedirectStandardError = !showConsoleWindow,
CreateNoWindow = !showConsoleWindow,
UseShellExecute = false,
Verb = "runas"
};

if (showConsoleWindow)
{
startInfo.WindowStyle =
ProcessWindowStyle.Normal;
}

var process = new Process { StartInfo = startInfo };
process.Start();

await process.StandardInput.WriteLineAsync(command);

if (showConsoleWindow)
{
var delayTask = Task.Delay(5000);
var exitTask = Task.Run(() => process.WaitForExit());
await Task.WhenAny(delayTask, exitTask);

if (!process.HasExited) process.CloseMainWindow();

return true;
}

process.StandardInput.Close();

await process.WaitForExitAsync();

var success = process.ExitCode == 0;
var error = await process.StandardError.ReadToEndAsync();

if (!success)
{
// Error message box
}
else
{
// Success message box
}

return success;
2 Replies
Dawid
Dawid13mo ago
Right now, when showConsoleWindow is true, I can't read output, so i just show it for 5sec and then close terminal window and return true, but I'd like it to read that output as It does when showConsoleWindow is false and catch eny errors and show message box with success or error message.
Accord
Accord13mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.