C#程序調用cmd執行命令

對於C#經過程序來調用cmd命令的操做,網上有不少相似的文章,但不少都不行,竟是漫天的拷貝。我本身測試整理了一下。html

代碼:shell

            string str = Console.ReadLine();

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操做系統shell啓動
            p.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息
            p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息
            p.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出
            p.StartInfo.CreateNoWindow = true;//不顯示程序窗口
            p.Start();//啓動程序

            //向cmd窗口發送輸入信息
            p.StandardInput.WriteLine(str + "&exit");

            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向標準輸入寫入要執行的命令。這裏使用&是批處理命令的符號,表示前面一個命令無論是否執行成功都執行後面(exit)命令,若是不執行exit命令,後面調用ReadToEnd()方法會假死
            //同類的符號還有&&和||前者表示必須前一個命令執行成功纔會執行後面的命令,後者表示必須前一個命令執行失敗纔會執行後面的命令



            //獲取cmd窗口的輸出信息
            string output = p.StandardOutput.ReadToEnd();

            //StreamReader reader = p.StandardOutput;
            //string line=reader.ReadLine();
            //while (!reader.EndOfStream)
            //{
            //    str += line + "  ";
            //    line = reader.ReadLine();
            //}

            p.WaitForExit();//等待程序執行完退出進程
            p.Close();


            Console.WriteLine(output);

程序運行結果:測試

 

須要提醒注意的一個地方就是:在前面的命令執行完成後,要加exit命令,不然後面調用ReadtoEnd()命令會假死。spa

我在以前測試的時候沒有加exit命令,輸入其餘命令後窗口就假死了,也沒有輸出內容。操作系統

對於執行cmd命令時如何以管理員身份運行,能夠看我上一篇文章: C#如何以管理員身份運行程序 - 酷小孩 - 博客園命令行

 

2014-7-28 新增:code

另外一種C#調用cmd命令的方法,不過這種方法在執行時會「閃一下」 黑窗口,各位在使用時能夠按喜愛來調用。orm

        /// <summary>
        /// 運行cmd命令
        /// 會顯示命令窗口
        /// </summary>
        /// <param name="cmdExe">指定應用程序的完整路徑</param>
        /// <param name="cmdStr">執行命令行參數</param>
        static bool RunCmd(string cmdExe, string cmdStr)
        {
            bool result = false;
            try
            {
                using (Process myPro = new Process())
                {
                    //指定啓動進程是調用的應用程序和命令行參數
                    ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr);
                    myPro.StartInfo = psi;
                    myPro.Start();
                    myPro.WaitForExit();
                    result = true;
                }
            }
            catch
            {

            }
            return result;
        }

        /// <summary>
        /// 運行cmd命令
        /// 不顯示命令窗口
        /// </summary>
        /// <param name="cmdExe">指定應用程序的完整路徑</param>
        /// <param name="cmdStr">執行命令行參數</param>
        static bool RunCmd2(string cmdExe, string cmdStr)
        {
            bool result = false;
            try
            {
                using (Process myPro = new Process())
                {
                    myPro.StartInfo.FileName = "cmd.exe";
                    myPro.StartInfo.UseShellExecute = false;
                    myPro.StartInfo.RedirectStandardInput = true;
                    myPro.StartInfo.RedirectStandardOutput = true;
                    myPro.StartInfo.RedirectStandardError = true;
                    myPro.StartInfo.CreateNoWindow = true;
                    myPro.Start();
                    //若是調用程序路徑中有空格時,cmd命令執行失敗,能夠用雙引號括起來 ,在這裏兩個引號表示一個引號(轉義)
                    string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit");
                  
                    myPro.StandardInput.WriteLine(str);
                    myPro.StandardInput.AutoFlush = true;
                    myPro.WaitForExit();

                    result = true;
                }
            }
            catch
            {

            }
            return result;
        }
    

 

 

轉載請註明出處。htm

相關文章
相關標籤/搜索