using System.Diagnostics; Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; //設定輸出結果導向 p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; //不顯示視窗 string cmdInput = "dir"; string cmdOutput = null; string cmdErr = null; p.Start(); //開始執行 p.StandardInput.WriteLine(cmdInput); p.StandardInput.WriteLine("exit"); cmdOutput = p.StandardOutput.ReadToEnd(); //將整個執行過程轉為字串 cmdErr = p.StandardError.ReadToEnd(); //將執行錯誤的訊息轉為字串 p.WaitForExit(); p.Close();
若執行大量資料時,要注意 WaitForExit() 一定要寫在 StandardOutput 之後,
// To avoid deadlocks, always read the output stream first and then wait. string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();
參考文件:https://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx