CMDHelper.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Diagnostics;
  2. using System.IO;
  3. namespace LJLib.Cmd
  4. {
  5. public static class CMDHelper
  6. {
  7. public static string RunWithReturn(string cmd, string workingdir = null)
  8. {
  9. using (Process p = new Process())
  10. {
  11. if (!string.IsNullOrEmpty(workingdir) && Directory.Exists(workingdir))
  12. {
  13. p.StartInfo.WorkingDirectory = workingdir;
  14. }
  15. RunCmd(p, cmd);
  16. string line = p.StandardOutput.ReadLine();
  17. while (line != cmd)
  18. {
  19. line = p.StandardOutput.ReadLine();
  20. }
  21. string rslt = string.Empty;
  22. line = p.StandardOutput.ReadLine();
  23. while (line != "exit")
  24. {
  25. if (string.IsNullOrEmpty(rslt))
  26. {
  27. rslt = line;
  28. }
  29. else
  30. {
  31. rslt += "\r\n" + line;
  32. }
  33. line = p.StandardOutput.ReadLine();
  34. }
  35. string errmsg = p.StandardError.ReadToEnd().Trim();
  36. if (!string.IsNullOrEmpty(errmsg))
  37. {
  38. rslt += "\r\nERROR:\r\n" + errmsg;
  39. }
  40. return rslt;
  41. }
  42. }
  43. //public static string RunWithReturn(string cmd, Encoding encoding)
  44. //{
  45. // Process p = new Process();
  46. // RunCmd(p, cmd);
  47. // string rslt = "";
  48. // byte[] St = new byte[1024];
  49. // using (MemoryStream ms = new MemoryStream())
  50. // {
  51. // int cnt = 0;
  52. // while ((cnt = p.StandardOutput.BaseStream.Read(St, 0, St.Length)) > 0)
  53. // {
  54. // ms.Write(St, 0, cnt);
  55. // }
  56. // St = ms.ToArray();
  57. // }
  58. // string msg = Encoding.UTF8.GetString(St);
  59. // using (StreamReader reader = new StreamReader(p.StandardOutput.BaseStream, encoding))
  60. // using (StreamReader errReader = new StreamReader(p.StandardError.BaseStream, encoding))
  61. // {
  62. // rslt += reader.ReadToEnd() + "\r\n" + errReader.ReadToEnd();
  63. // }
  64. // return rslt;
  65. //}
  66. public static void Run(string cmd)
  67. {
  68. using (Process p = new Process())
  69. {
  70. RunCmd(p, cmd);
  71. }
  72. }
  73. private static void RunCmd(Process p, string cmd)
  74. {
  75. p.StartInfo.FileName = "cmd.exe";
  76. p.StartInfo.UseShellExecute = false;
  77. p.StartInfo.RedirectStandardInput = true;
  78. p.StartInfo.RedirectStandardOutput = true;
  79. p.StartInfo.RedirectStandardError = true;
  80. p.StartInfo.CreateNoWindow = true;
  81. p.Start();
  82. p.StandardInput.WriteLine("echo off");
  83. p.StandardInput.WriteLine(cmd);
  84. p.StandardInput.WriteLine("exit");
  85. }
  86. }
  87. }