Files
basic-computer-games/00_Utilities/DotnetUtils/DotnetUtils/Methods.cs
2022-01-16 03:27:32 +02:00

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}" :
"");
}