天天看點

.NET啟動CMD執行(轉載)

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);