zoukankan      html  css  js  c++  java
  • C#执行cmd命令

     1 public class Console : IRun
     2     {
     3         public Console(){
     4             this.TimeOut = 3000;
     5         }
     6         public string Result
     7         {
     8             get;
     9             set;
    10         }
    11         public string Error
    12         {
    13             get;
    14             set;
    15         }
    16         public int TimeOut
    17         {
    18             get;
    19             set;
    20         }
    21         public string[] Cmds
    22         {
    23             get;
    24             set;
    25         }
    26         #region IRun 成员
    27 
    28         public void Run()
    29         {
    30             using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    31             {
    32                
    33                 process.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd")
    34                 {
    35                     RedirectStandardOutput = true,
    36                     RedirectStandardInput = true,
    37                     CreateNoWindow = true,
    38                     UseShellExecute = false,
    39                     RedirectStandardError = true
    40                 };
    41 
    42                 process.Start();
    43                 System.Text.StringBuilder cmd = new StringBuilder();
    44                 foreach (string arg in Cmds)
    45                 {
    46                     if (string.IsNullOrEmpty(arg))
    47                     {
    48                         continue;
    49                     }
    50                     process.StandardInput.WriteLine(arg);
    51                     cmd.Append(arg);
    52                 }
    53                 process.StandardInput.WriteLine(@"exit");
    54                 try
    55                 {
    56                     process.WaitForExit(Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["CMDTimeOut"]));
    57                 }
    58                 catch
    59                 {
    60                     process.WaitForExit();
    61                 }
    62                 this.Result = process.StandardOutput.ReadToEnd();
    63                 this.Error = process.StandardError.ReadToEnd();
    64                 
    65                 process.Close();
    66                 if (!string.IsNullOrEmpty(this.Error))
    67                 {
    68                     throw new Exception(string.Format("出错命令:
    {0}
    {1}", cmd.ToString(), this.Error));
    69                 }
    70             }
    71         }
    72 
    73         #endregion
    74     }
  • 相关阅读:
    [NOI2002]银河英雄传说
    Splay普及版
    线段树普及版
    长连接与短连接
    【HTTP】中Get/Post请求区别
    【HTML】知识笔记
    SVN使用教程总结
    《人生只有一次,去做自己喜欢的事》读书笔记
    【HTTP】无状态无连接的含义
    【HTML】解析原理
  • 原文地址:https://www.cnblogs.com/yomho/p/3731840.html
Copyright © 2011-2022 走看看