12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Runtime.InteropServices;
- namespace KeyraysFramework.Tools
- {
- public static class ProcessHelper
- {
- public static Process Run(string exe, string arguments, string workingDirectory = ".", bool waitExit = false)
- {
- try
- {
- bool redirectStandardOutput = true;
- bool redirectStandardError = true;
- bool useShellExecute = false;
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- redirectStandardOutput = false;
- redirectStandardError = false;
- useShellExecute = true;
- }
- if (waitExit)
- {
- redirectStandardOutput = true;
- redirectStandardError = true;
- useShellExecute = false;
- }
- ProcessStartInfo info = new ProcessStartInfo
- {
- FileName = exe,
- Arguments = arguments,
- CreateNoWindow = true,
- UseShellExecute = useShellExecute,
- WorkingDirectory = workingDirectory,
- RedirectStandardOutput = redirectStandardOutput,
- RedirectStandardError = redirectStandardError,
- };
- Process process = Process.Start(info);
- if (waitExit)
- {
- process.WaitForExit();
- if (process.ExitCode != 0)
- {
- throw new Exception($"{process.StandardOutput.ReadToEnd()} {process.StandardError.ReadToEnd()}");
- }
- }
- return process;
- }
- catch (Exception e)
- {
- throw new Exception($"dir: {Path.GetFullPath(workingDirectory)}, command: {exe} {arguments}", e);
- }
- }
- }
- }
|