经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
C#调用Windows CMD命令并返回输出结果
来源:cnblogs  作者:千丶吻  时间:2018/11/20 10:42:01  对本文有异议

 

  1. private static string InvokeExcute(string Command)
  2. {
  3. Command = Command.Trim().TrimEnd('&') + "&exit";
  4. using (Process p = new Process())
  5. {
  6. p.StartInfo.FileName = "cmd.exe";
  7. p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
  8. p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
  9. p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
  10. p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  11. p.StartInfo.CreateNoWindow = true; //不显示程序窗口
  12. p.Start();//启动程序
  13. //向cmd窗口写入命令
  14. p.StandardInput.WriteLine(Command);
  15. p.StandardInput.AutoFlush = true;
  16. //获取cmd窗口的输出信息
  17. StreamReader reader = p.StandardOutput;//截取输出流
  18. string str = reader.ReadToEnd();
  19. p.WaitForExit();//等待程序执行完退出进程
  20. p.Close();
  21. return str;
  22. }
  23. }

 

例子:

  1. string str = InvokeExcute("ipconfig");
  2. Console.WriteLine(str);
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号