WindowsCommand.cs 2.7 KB

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