Innovenergy_trunk/csharp/Lib/SysTools/Edges/SysCommandToProcess.cs

72 lines
2.2 KiB
C#

using System.Diagnostics;
using System.Reactive.Linq;
using System.Text;
using InnovEnergy.Lib.SysTools.Process;
namespace InnovEnergy.Lib.SysTools.Edges;
public static class SysCommandToProcess
{
public static ProcessResult ExecuteBlocking(this SysCommand command, Dictionary<String, String> variables = null, Boolean logToConsole =false)
{
var process = command.ToAsyncProcess(variables, logToConsole);
var stdOut = new List<String>();
var stdErr = new List<String>();
var output = new StringBuilder();
process.StandardOut.Subscribe(o =>
{
stdOut.Add(o);
output.AppendLine(o);
});
process.StandardErr.Subscribe(e =>
{
stdErr.Add(e);
output.AppendLine(e);
});
process.Run();
var exitCode = process.ExitCode.Wait();
process.Terminate();
return new ProcessResult(exitCode, stdOut, stdErr, output.ToString());
}
public static AsyncProcess ToAsyncProcess(this SysCommand command, Dictionary<String, String> variables = null, Boolean logToConsole = false)
{
return new AsyncProcess(command, variables, logToConsole);
}
public static SyncProcess ToSyncProcess(this SysCommand command, Dictionary<String, String> variables = null, Boolean logToConsole = false)
{
return new SyncProcess(command, variables, logToConsole);
}
public static System.Diagnostics.Process ToConsoleProcess(this SysCommand command, Dictionary<String, String> variables = null)
{
var startInfo = new ProcessStartInfo
{
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false,
UseShellExecute = false,
CreateNoWindow = true,
Arguments = command.Args,
FileName = command.Path,
};
if (variables != null)
foreach (var kv in variables)
startInfo.EnvironmentVariables[kv.Key] = kv.Value;
return new System.Diagnostics.Process
{
StartInfo = startInfo,
EnableRaisingEvents = true
};
}
}