using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using xCommons.Extensions; using xExceptions.Attributes; using xExceptions.Constants; namespace xCommons.Helpers { /// /// Several OS Type ... /// public enum XOSType { [StringValue("Unknown")] XUnknown, [StringValue("Mac")] XMacOs, [StringValue("Linux")] XLinux, [StringValue("Windows")] XWindows, [StringValue("FreeBSD")] XFreeBSD, } /// /// OS Command Execution Result ... /// public class XOSCMDResult { /// /// Execution Result ... /// /// public string Result { get; set; } /// /// Execution Error ... /// /// public string Error { get; set; } } /// /// a Helper Class which Provides OS Command Executions ... /// public static partial class XOsHelper { /// /// Retrieve OS Type ... /// /// public static XOSType GetOSType() { // XOSType result = XOSType.XUnknown; // if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { result = XOSType.XMacOs; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { result = XOSType.XLinux; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { result = XOSType.XWindows; } // else if (RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) // { // result = XOSType.XFreeBSD; // } // return result; } /// /// Retrieve OS Description ... /// /// public static string GetOSDescription() { // var result = RuntimeInformation.OSDescription; return result; } /// /// Execute an Specified Command ... /// /// Specified Command /// Command Arguments /// public static async Task Execute( string cmd, string args ) { // var result = new XOSCMDResult { Error = "Unknown", }; // try { // // Validate CMD ... var isValid = !cmd.IsNullOrEmpty(); if (!isValid) { XException.InvalidArgs.Throw(); } // // Validate OS Type ... XOSType osType = GetOSType(); isValid = osType != XOSType.XUnknown; if (!isValid) { XException.InvalidArgs.Throw(); } // return await Task.Run(() => { // ProcessStartInfo psi = new ProcessStartInfo(); // psi.FileName = cmd; psi.Arguments = args; psi.UseShellExecute = false; psi.RedirectStandardError = true; psi.RedirectStandardOutput = true; // Process process = Process.Start(psi); // // Read the output string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); // process.WaitForExit(); // result = new XOSCMDResult { Error = error, Result = output, }; // return result; }); } catch (Exception ex) { result.Error = ex.Message; } // return result; } } }