ProcessHelper.cs 2.1 KB

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