C#程序調用cmd執行命令


 1 string str = Console.ReadLine();
 2 
 3             System.Diagnostics.Process p = new System.Diagnostics.Process();
 4             p.StartInfo.FileName = "cmd.exe";
 5             p.StartInfo.UseShellExecute = false;    //是否使用操作系統shell啟動
 6             p.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息
 7             p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息
 8             p.StartInfo.RedirectStandardError = true;//重定向標准錯誤輸出
 9             p.StartInfo.CreateNoWindow = true;//不顯示程序窗口
10             p.Start();//啟動程序
11 
12             //向cmd窗口發送輸入信息
13             p.StandardInput.WriteLine(str + "&exit");
14 
15             p.StandardInput.AutoFlush = true;
16             //p.StandardInput.WriteLine("exit");
17             //向標准輸入寫入要執行的命令。這里使用&是批處理命令的符號,表示前面一個命令不管是否執行成功都執行后面(exit)命令,如果不執行exit命令,后面調用ReadToEnd()方法會假死
18             //同類的符號還有&&和||前者表示必須前一個命令執行成功才會執行后面的命令,后者表示必須前一個命令執行失敗才會執行后面的命令
19 
20 
21 
22             //獲取cmd窗口的輸出信息
23             string output = p.StandardOutput.ReadToEnd();
24 
25             //StreamReader reader = p.StandardOutput;
26             //string line=reader.ReadLine();
27             //while (!reader.EndOfStream)
28             //{
29             //    str += line + "  ";
30             //    line = reader.ReadLine();
31             //}
32 
33             p.WaitForExit();//等待程序執行完退出進程
34             p.Close();
35 
36 
37             Console.WriteLine(output);

 

需要提醒注意的一個地方就是:在前面的命令執行完成后,要加exit命令,否則后面調用ReadtoEnd()命令會假死。

我在之前測試的時候沒有加exit命令,輸入其他命令后窗口就假死了,也沒有輸出內容。

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

 

2014-7-28 新增:

另一種C#調用cmd命令的方法,不過這種方法在執行時會“閃一下” 黑窗口,各位在使用時可以按喜好來調用。

/// <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;
        }

 

 


作者:酷小孩 

出處:http://www.cnblogs.com/babycool/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM