【C#】调用DOS命令

1 public interface IRunConsole
2     {
3         void Run();
4     }

 

public abstract class RunConsole:IRunConsole
    {
        public abstract string[] Args { get; }
        public abstract string FileName { get; }//CMD
        public string result;
        public string error;
        public virtual int WaitExitedTime {
            get {
                return 60000;
            }
        }
        #region IRunConsole 成员

        public void Run()
        {
            using(System.Diagnostics.Process process = new System.Diagnostics.Process()){
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(FileName)
                {
                    RedirectStandardOutput=true,
                    RedirectStandardInput=true,
                    CreateNoWindow=true,
                    UseShellExecute=false,
                    RedirectStandardError = true
                };
                process.Start();
                foreach (string arg in Args) {
                    process.StandardInput.WriteLine(arg);
                }
                
                process.StandardInput.WriteLine(@"exit");
                process.WaitForExit();
                this.result = process.StandardOutput.ReadToEnd();
                this.error = process.StandardError.ReadToEnd();
                process.Close();
                if (!string.IsNullOrEmpty(this.error)) {
                    throw new Exception(this.error);
                }
            }
        }

        #endregion
    }

 

 1 public class RunDelDirectory : RunConsole
 2     {
 3         public string DirPath
 4         {
 5             get;
 6             set;
 7         }
 8         public override string[] Args
 9         {
10             get {
11                 return new string[]{
12                   string.Format("rd /s/q {0}",this.DirPath)  
13                 };
14             }
15         }
16 
17         public override string FileName
18         {
19             get { return "cmd"; }
20         }
21     }

 

posted @ 2013-06-21 10:01  哈哈好玩  阅读(352)  评论(0编辑  收藏  举报