using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace AyaNova.Util { public static class RunProgram { public static string Run(string cmd, string arguments) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return RunWindows(cmd, arguments); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return RunOSX(cmd, arguments); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return RunLinuxBash(cmd, arguments); } else { throw new PlatformNotSupportedException(); } } private static string RunWindows(string cmd, string arguments) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = cmd, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, }; process.Start(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } } private static string RunLinuxBash(string cmd, string arguments) { var escapedArgs = $"{cmd} {arguments}".Replace("\"", "\\\""); using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = "/bin/bash", Arguments = $"-c \"{escapedArgs}\"", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, }; process.Start(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } } private static string RunOSX(string cmd, string arguments) { using (var process = new Process()) { process.StartInfo = new ProcessStartInfo { FileName = cmd, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, }; process.Start(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return result; } } } }