ProcessUtil.cs 2.1 KB

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