WindowsCommand.cs 3.6 KB

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