ShellHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System.Diagnostics;
  12. using System.Text;
  13. /// <summary> Misc helper methods for running shell commands. </summary>
  14. public static class ShellHelper
  15. {
  16. /// <summary> Run a shell command. </summary>
  17. /// <param name="fileName"> File name for the executable.</param>
  18. /// <param name="arguments"> Command line arguments, space delimited.</param>
  19. /// <param name="output"> [out] Filled out with the result as printed to stdout.</param>
  20. /// <param name="error"> [out] Filled out with the result as printed to stderr.</param>
  21. public static void RunCommand(string fileName, string arguments, out string output, out string error)
  22. {
  23. using (var process = new Process())
  24. {
  25. var startInfo = new ProcessStartInfo(fileName, arguments);
  26. startInfo.UseShellExecute = false;
  27. startInfo.RedirectStandardError = true;
  28. startInfo.RedirectStandardOutput = true;
  29. startInfo.CreateNoWindow = true;
  30. process.StartInfo = startInfo;
  31. var errorBuilder = new StringBuilder();
  32. process.ErrorDataReceived += (sender, ef) => errorBuilder.AppendLine(ef.Data);
  33. process.Start();
  34. process.BeginOutputReadLine();
  35. process.BeginErrorReadLine();
  36. process.WaitForExit();
  37. var existcode = process.ExitCode;
  38. process.Close();
  39. // Trims the output strings to make comparison easier.
  40. output = existcode.ToString();
  41. error = errorBuilder.ToString().Trim();
  42. }
  43. }
  44. /// <summary> Run a shell command. </summary>
  45. /// <param name="fileName"> File name for the executable.</param>
  46. /// <param name="arguments"> Command line arguments, space delimited.</param>
  47. public static void RunCommand(string fileName, string arguments)
  48. {
  49. using (var process = new Process())
  50. {
  51. var startInfo = new ProcessStartInfo(fileName, arguments);
  52. startInfo.CreateNoWindow = false;
  53. process.StartInfo = startInfo;
  54. process.Start();
  55. }
  56. }
  57. }
  58. }