首页 > 代码库 > C#执行cmd命令
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("出错命令:\r\n{0}\r\n{1}", cmd.ToString(), this.Error)); 69 } 70 } 71 } 72 73 #endregion 74 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。