应用中执行一个控制台命令 - C#

最近又开始用.Net平台做程序了,想想换了这么多的平台,真是够折腾的,不过没有办法啊,为了混饭吃,只能这样子。希望我们的程序员以后可以不像现在这样残,嘿嘿。

下面是一个很实用的程序片段,可以通过这个函数启动执行一个控制台的命令。

        /// <summary>
        /// Runs a command with supplied araguments.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="arguments"></param>
        private void runShellCommand(String command, String arguments)
        {
            Process process = new Process();
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.FileName = command;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            while (process.HasExited == false)
            {
                Thread.Sleep(1000);
                if (ApplicationStatus.IsAborting == true)
                {
                    process.Kill();
                    break;
                }
            }
        }

posted on 2010-11-03 15:18  FREE LOOP  阅读(1007)  评论(0编辑  收藏  举报

导航