当前位置:   article > 正文

C#获取命令行输出内容_c# 获取命令行输出

c# 获取命令行输出

获取命令行输出内容的方式有传统和异步两种方式。

传统方式:

  1. public static void RunExe(string exePath, string arguments, out string output, out string error)
  2. {
  3. using (Process process = new System.Diagnostics.Process())
  4. {
  5. process.StartInfo.FileName = exePath;
  6. process.StartInfo.Arguments = arguments;
  7. // 必须禁用操作系统外壳程序
  8. process.StartInfo.UseShellExecute = false;
  9. process.StartInfo.CreateNoWindow = true;
  10. process.StartInfo.RedirectStandardOutput = true;
  11. process.StartInfo.RedirectStandardError = true;
  12. process.Start();
  13. output = process.StandardOutput.ReadToEnd();
  14. error = process.StandardError.ReadToEnd();
  15. process.WaitForExit();
  16. process.Close();
  17. }
  18. }

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. string output;
  6. string error;
  7. CMD.RunExe("ping", "www.baidu.com",out output,out error);
  8. Console.WriteLine(output +"\n"+ error);
  9. }
  10. }



异步方式:

  1. /// <summary>
  2. /// 执行一条command命令
  3. /// </summary>
  4. /// <param name="command">需要执行的Command</param>
  5. /// <param name="output">输出</param>
  6. /// <param name="error">错误</param>
  7. public static void ExecuteCommand(string command, out string output, out string error)
  8. {
  9. try
  10. {
  11. //创建一个进程
  12. Process process = new Process();
  13. process.StartInfo.FileName = command;
  14. // 必须禁用操作系统外壳程序
  15. process.StartInfo.UseShellExecute = false;
  16. process.StartInfo.CreateNoWindow = true;
  17. process.StartInfo.RedirectStandardOutput = true;
  18. process.StartInfo.RedirectStandardError = true;
  19. //启动进程
  20. process.Start();
  21. //准备读出输出流和错误流
  22. string outputData = string.Empty;
  23. string errorData = string.Empty;
  24. process.BeginOutputReadLine();
  25. process.BeginErrorReadLine();
  26. process.OutputDataReceived += (sender, e) =>
  27. {
  28. outputData += (e.Data + "\n");
  29. };
  30. process.ErrorDataReceived += (sender, e) =>
  31. {
  32. errorData += (e.Data + "\n");
  33. };
  34. //等待退出
  35. process.WaitForExit();
  36. //关闭进程
  37. process.Close();
  38. //返回流结果
  39. output = outputData;
  40. error = errorData;
  41. }
  42. catch (Exception)
  43. {
  44. output = null;
  45. error = null;
  46. }
  47. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/631249
推荐阅读
相关标签
  

闽ICP备14008679号