命令列呼叫bat檔案

xuxubaby發表於2013-10-22

           // Get the full file path
            string strFilePath = @"E:\yuht\wk\10\22\test.bat";  //得到bat 檔案全路徑名

            // Create the ProcessInfo object
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe"); //啟動cmd.exe
            psi.UseShellExecute = false;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = @"E:\yuht\wk\10\22\"; //設定cmd.exe 的工作目錄
            // Start the process
            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); //啟動
            // Open the batch file for reading
            System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath); //讀bat 檔案
            // Attach the in for writing
            System.IO.StreamWriter sIn = proc.StandardInput;
            // Write each line of the batch file to standard input
            while(strm.Peek() != -1)
            {
             sIn.WriteLine(strm.ReadLine());  //寫入
            }
            strm.Close();
            // Exit CMD.EXE
            sIn.WriteLine("DEL " + strFilePath);   //執行完刪除bat
            sIn.WriteLine("EXIT");
            // Close the process
            proc.Close();
            // Close the io Streams;
            sIn.Close();

相關文章