ProcessHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. namespace KeyraysFramework.Tools
  6. {
  7. public static class ProcessHelper
  8. {
  9. public static Process Run(string exe, string arguments, string workingDirectory = ".", bool waitExit = false)
  10. {
  11. try
  12. {
  13. bool redirectStandardOutput = true;
  14. bool redirectStandardError = true;
  15. bool useShellExecute = false;
  16. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  17. {
  18. redirectStandardOutput = false;
  19. redirectStandardError = false;
  20. useShellExecute = true;
  21. }
  22. if (waitExit)
  23. {
  24. redirectStandardOutput = true;
  25. redirectStandardError = true;
  26. useShellExecute = false;
  27. }
  28. ProcessStartInfo info = new ProcessStartInfo
  29. {
  30. FileName = exe,
  31. Arguments = arguments,
  32. CreateNoWindow = true,
  33. UseShellExecute = useShellExecute,
  34. WorkingDirectory = workingDirectory,
  35. RedirectStandardOutput = redirectStandardOutput,
  36. RedirectStandardError = redirectStandardError,
  37. };
  38. Process process = Process.Start(info);
  39. if (waitExit)
  40. {
  41. process.WaitForExit();
  42. if (process.ExitCode != 0)
  43. {
  44. throw new Exception($"{process.StandardOutput.ReadToEnd()} {process.StandardError.ReadToEnd()}");
  45. }
  46. }
  47. return process;
  48. }
  49. catch (Exception e)
  50. {
  51. throw new Exception($"dir: {Path.GetFullPath(workingDirectory)}, command: {exe} {arguments}", e);
  52. }
  53. }
  54. }
  55. }