首页 > 技术文章 > 通过cmd执行命令例子

lvdong-1986 2014-12-25 18:12 原文

public class Cmd

{

        /// <summary>

        /// 执行Cmd命令

        /// </summary>

        /// <param name="workingDirectory">要启动的进程的目录</param>

        /// <param name="command">要执行的命令</param>

        public static void StartCmd(String workingDirectory, String command)

        {

            Process p = new Process();

            p.StartInfo.FileName = "cmd.exe";//确定程序名

            p.StartInfo.WorkingDirectory = workingDirectory;

            p.StartInfo.UseShellExecute = false;//Shell的使用

            p.StartInfo.RedirectStandardInput = true;//重定向输入

            p.StartInfo.RedirectStandardOutput = true;//重定向输出

            p.StartInfo.RedirectStandardError = true;//重定向输出错误

            p.StartInfo.CreateNoWindow = true;//设置置不显示示窗口

            p.Start();

            p.StandardInput.WriteLine(command);//也可以用这种方式输入要执行的命令

            p.StandardInput.WriteLine("exit");

            p.WaitForExit();//不加此句则不会等待,加了此句相当于异步等待。

        }

}

推荐阅读