ProcessUtil.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using log4net;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace DeviceCenter
  8. {
  9. class ProcessUtil
  10. {
  11. public static readonly ILog log = LogManager.GetLogger("ProcessUtil");
  12. public static string run(string cmd)
  13. {
  14. System.Diagnostics.Process p = new System.Diagnostics.Process();
  15. p.StartInfo.FileName = "cmd.exe";
  16. p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
  17. p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
  18. p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
  19. p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
  20. p.StartInfo.CreateNoWindow = true;//不显示程序窗口
  21. p.StartInfo.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
  22. p.Start();//启动程序
  23. log.Info("run command: "+ cmd + "&exit");
  24. //向cmd窗口发送输入信息
  25. p.StandardInput.WriteLine(cmd + "&exit");
  26. p.StandardInput.AutoFlush = true;
  27. //p.StandardInput.WriteLine("exit");
  28. //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
  29. //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令
  30. //获取cmd窗口的输出信息
  31. string output = p.StandardOutput.ReadToEnd();
  32. //StreamReader reader = p.StandardOutput;
  33. //string line=reader.ReadLine();
  34. //while (!reader.EndOfStream)
  35. //{
  36. // str += line + " ";
  37. // line = reader.ReadLine();
  38. //}
  39. p.WaitForExit();//等待程序执行完退出进程
  40. p.Close();
  41. log.Info("output: " + output);
  42. return output;
  43. }
  44. }
  45. }