ShellHelper.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5. namespace Infrastructure
  6. {
  7. public class ShellHelper
  8. {
  9. /// <summary>
  10. /// linux 系统命令
  11. /// </summary>
  12. /// <param name="command"></param>
  13. /// <returns></returns>
  14. public static string Bash(string command)
  15. {
  16. var escapedArgs = command.Replace("\"", "\\\"");
  17. var process = new Process()
  18. {
  19. StartInfo = new ProcessStartInfo
  20. {
  21. FileName = "/bin/bash",
  22. Arguments = $"-c \"{escapedArgs}\"",
  23. RedirectStandardOutput = true,
  24. UseShellExecute = false,
  25. CreateNoWindow = true,
  26. }
  27. };
  28. process.Start();
  29. string result = process.StandardOutput.ReadToEnd();
  30. process.WaitForExit();
  31. process.Dispose();
  32. return result;
  33. }
  34. /// <summary>
  35. /// windows系统命令
  36. /// </summary>
  37. /// <param name="fileName"></param>
  38. /// <param name="args"></param>
  39. /// <returns></returns>
  40. public static string Cmd(string fileName, string args)
  41. {
  42. string output = string.Empty;
  43. var info = new ProcessStartInfo();
  44. info.FileName = fileName;
  45. info.Arguments = args;
  46. info.RedirectStandardOutput = true;
  47. using (var process = Process.Start(info))
  48. {
  49. output = process.StandardOutput.ReadToEnd();
  50. }
  51. return output;
  52. }
  53. }
  54. }