WindowsCommand.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.ComponentModel;
  3. using System.Diagnostics;
  4. namespace Masuit.Tools.Win32
  5. {
  6. /// <summary>
  7. /// 命令提示符
  8. /// </summary>
  9. public static class WindowsCommand
  10. {
  11. /// <summary>
  12. /// 执行一个控制台程序,并获取在控制台返回的数据
  13. /// </summary>
  14. /// <param name="dosCommand">dos/cmd命令</param>
  15. /// <param name="outtime">等待执行时间毫秒值,默认不等待</param>
  16. /// <returns>控制台输出信息</returns>
  17. /// <exception cref="SystemException">尚未设置进程 <see cref="P:System.Diagnostics.Process.Id" />,而且不存在可从其确定 <see cref="P:System.Diagnostics.Process.Id" /> 属性的 <see cref="P:System.Diagnostics.Process.Handle" />。- 或 -没有与此 <see cref="T:System.Diagnostics.Process" /> 对象关联的进程。- 或 -您正尝试为远程计算机上运行的进程调用 <see cref="M:System.Diagnostics.Process.WaitForExit(System.Int32)" />。此方法仅对本地计算机上运行的进程可用。</exception>
  18. /// <exception cref="Win32Exception">未能访问该等待设置。</exception>
  19. /// <exception cref="Exception">命令参数无效,必须传入一个控制台能被cmd.exe可执行程序; 如:ping 127.0.0.1</exception>
  20. public static string Execute(string dosCommand, int outtime = 0)
  21. {
  22. string output = "";
  23. if (!string.IsNullOrEmpty(dosCommand))
  24. {
  25. using var process = new Process();
  26. ProcessStartInfo startinfo = new ProcessStartInfo(); //创建进程时使用的一组值,如下面的属性
  27. startinfo.FileName = "cmd.exe"; //设定需要执行的命令程序
  28. //以下是隐藏cmd窗口的方法
  29. startinfo.Arguments = "/c" + dosCommand; //设定参数,要输入到命令程序的字符,其中"/c"表示执行完命令后马上退出
  30. startinfo.UseShellExecute = false; //不使用系统外壳程序启动
  31. startinfo.RedirectStandardInput = false; //不重定向输入
  32. startinfo.RedirectStandardOutput = true; //重定向输出,而不是默认的显示在dos控制台上
  33. startinfo.CreateNoWindow = true; //不创建窗口
  34. process.StartInfo = startinfo;
  35. if (process.Start()) //开始进程
  36. {
  37. if (outtime == 0)
  38. {
  39. process.WaitForExit();
  40. }
  41. else
  42. {
  43. process.WaitForExit(outtime);
  44. }
  45. output = process.StandardOutput.ReadToEnd(); //读取进程的输出
  46. }
  47. return output;
  48. }
  49. throw new Exception("命令参数无效,必须传入一个控制台能被cmd.exe可执行程序;\n如:ping 127.0.0.1");
  50. }
  51. }
  52. }