码迷,mamicode.com
首页 > 其他好文 > 详细

C#执行cmd命令

时间:2014-05-19 10:54:35      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

bubuko.com,布布扣
 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     }
bubuko.com,布布扣

 

C#执行cmd命令,布布扣,bubuko.com

C#执行cmd命令

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/yomho/p/3731840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!