黑马程序员技术交流社区

标题: c#执行外部命令示例分享 [打印本页]

作者: 陈君    时间: 2014-8-31 22:45
标题: c#执行外部命令示例分享
c#执行外部命令示例分享,大家参考使用吧

  1. String Command = @"python test.py";
  2. String Output = Execute.run(Command);
  3. Console.WriteLine(Output);
  4. <DIV class=blockcode>
  5. <BLOCKQUOTE>
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. //using before change the namespace
  13. namespace test.utility
  14. {
  15. class Execute
  16. {
  17. public static String run(String Command)
  18. {
  19. String Output = null;
  20. if (Command != null && !Command.Equals(""))
  21. {
  22. Process process = new Process();
  23. ProcessStartInfo processStartInfo = new ProcessStartInfo();
  24. processStartInfo.FileName = "cmd.exe";
  25. //no create the cmd windows
  26. processStartInfo.CreateNoWindow = true;
  27. processStartInfo.RedirectStandardInput = true;
  28. processStartInfo.RedirectStandardOutput = true;
  29. processStartInfo.RedirectStandardError = true;
  30. processStartInfo.UseShellExecute = false;
  31. process.StartInfo = processStartInfo;
  32. try
  33. {
  34. process.Start();
  35. process.StandardInput.WriteLine(Command);
  36. process.StandardInput.WriteLine("exit");
  37. process.WaitForExit(30 * 1000);
  38. Output = process.StandardOutput.ReadToEnd();
  39. }
  40. catch (Exception e)
  41. {
  42. process.Close();
  43. return e.ToString();
  44. }
  45. finally
  46. {
  47. process.Close();
  48. }
  49. }
  50. return ContextFilter(Output);
  51. }
  52. public static String ContextFilter(String Output)
  53. {
  54. Regex regex_end = new Regex("^[^^]*#end");
  55. Match match = regex_end.Match(Output);
  56. Regex regex_begin = new Regex("^[^^]*?#begin\r\n");
  57. String result = regex_begin.Replace(match.Value, "");
  58. Regex regex_tar = new Regex("\r\n#end$");
  59. result = regex_tar.Replace(result,"");
  60. return result;
  61. }
  62. }
  63. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2