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     }

 

posted @ 2014-05-16 11:41  哈哈好玩  阅读(2285)  评论(0编辑  收藏  举报