mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-22 07:10:42 -08:00
57 lines
1.8 KiB
C#
57 lines
1.8 KiB
C#
using System.Diagnostics;
|
|
|
|
namespace DotnetUtils;
|
|
|
|
public static class Methods {
|
|
public static ProcessResult RunProcess(string filename, string arguments) {
|
|
var process = new Process() {
|
|
StartInfo = {
|
|
FileName = filename,
|
|
Arguments = arguments,
|
|
UseShellExecute = false,
|
|
CreateNoWindow = true,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
},
|
|
EnableRaisingEvents = true
|
|
};
|
|
return RunProcess(process);
|
|
}
|
|
|
|
public static ProcessResult RunProcess(Process process, string input = "") {
|
|
var (output, error) = ("", "");
|
|
var (redirectOut, redirectErr) = (
|
|
process.StartInfo.RedirectStandardOutput,
|
|
process.StartInfo.RedirectStandardError
|
|
);
|
|
if (redirectOut) {
|
|
process.OutputDataReceived += (s, ea) => output += ea.Data + "\n";
|
|
}
|
|
if (redirectErr) {
|
|
process.ErrorDataReceived += (s, ea) => error += ea.Data + "\n";
|
|
}
|
|
|
|
if (!process.Start()) {
|
|
throw new InvalidOperationException();
|
|
};
|
|
|
|
if (redirectOut) { process.BeginOutputReadLine(); }
|
|
if (redirectErr) { process.BeginErrorReadLine(); }
|
|
if (!string.IsNullOrEmpty(input)) {
|
|
process.StandardInput.WriteLine(input);
|
|
process.StandardInput.Close();
|
|
}
|
|
process.WaitForExit();
|
|
return new ProcessResult(process.ExitCode, output, error);
|
|
}
|
|
}
|
|
|
|
public sealed record ProcessResult(int ExitCode, string StdOut, string StdErr) {
|
|
public override string? ToString() =>
|
|
StdOut +
|
|
(StdOut is not (null or "") && ExitCode > 0 ? "\n" : "") +
|
|
(ExitCode > 0 ?
|
|
$"{ExitCode}\n{StdErr}" :
|
|
"");
|
|
}
|