1.c# 調用CMD窗體執行命令 阻塞執行, 並在最后執行完后一次性輸出執行結果
public static string RunCmd(string cmd) { //string strInput = Console.ReadLine(); Process p = new Process(); //設置要啟動的應用程序 p.StartInfo.FileName = "cmd.exe"; //是否使用操作系統shell啟動 p.StartInfo.UseShellExecute = false; // 接受來自調用程序的輸入信息 p.StartInfo.RedirectStandardInput = true; //輸出信息 p.StartInfo.RedirectStandardOutput = true; // 輸出錯誤 p.StartInfo.RedirectStandardError = true; //不顯示程序窗口 p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Normal; //啟動程序 p.Start(); //向cmd窗口發送輸入信息 p.StandardInput.WriteLine(cmd + "&exit"); p.StandardInput.AutoFlush = true; //獲取輸出信息 string strOuput = p.StandardOutput.ReadToEnd(); //等待程序執行完退出進程 p.WaitForExit(); p.Close(); return strOuput; //Console.WriteLine(strOuput); }
2. 調用CMD窗體執行命令 實時獲取執行結果並輸出
public string RunCmd(string cmd) { try { //string strInput = Console.ReadLine(); Process p = new Process(); //設置要啟動的應用程序 p.StartInfo.FileName = "cmd.exe"; //是否使用操作系統shell啟動 p.StartInfo.UseShellExecute = false; // 接受來自調用程序的輸入信息 p.StartInfo.RedirectStandardInput = true; //輸出信息 p.StartInfo.RedirectStandardOutput = true; // 輸出錯誤 p.StartInfo.RedirectStandardError = true; //不顯示程序窗口 p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Normal; p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived); //啟用Exited事件 p.EnableRaisingEvents = true; p.Exited += new EventHandler(Process_Exited); //啟動程序 p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.StandardInput.AutoFlush = true; //輸入命令 p.StandardInput.WriteLine(cmd); p.StandardInput.WriteLine("exit"); //獲取輸出信息 // string strOuput = p.StandardOutput.ReadToEnd(); //等待程序執行完退出進程 //p.WaitForExit(); //p.Close(); // return strOuput; return string.Empty; } catch (Exception ex) { throw ex; } } private void p_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { Console.WriteLine(e.Data); } } private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data != null) { Console.WriteLine(e.Data); } } private void Process_Exited(object sender, EventArgs e) {
Console.WriteLine("命令執行完畢");
}