從當前目錄下的cmd.txt文件中讀取DOS命令並執行,一行一個命令
C#代碼:
string result=string.Empty; string[] all = File.ReadAllLines(@"cmd.txt"); RunCMDCommand(out result, all); MessageBox.Show(result);
public void RunCMDCommand(out string outPut, params string[] command) { using (Process pc = new Process()) { pc.StartInfo.FileName = "cmd.exe"; pc.StartInfo.CreateNoWindow = true;//隱藏窗口運行 pc.StartInfo.RedirectStandardError = true;//重定向錯誤流 pc.StartInfo.RedirectStandardInput = true;//重定向輸入流 pc.StartInfo.RedirectStandardOutput = true;//重定向輸出流 pc.StartInfo.UseShellExecute = false; pc.Start(); int lenght = command.Length; foreach (string com in command) { pc.StandardInput.WriteLine(com);//輸入CMD命令 } pc.StandardInput.WriteLine("exit");//結束執行,很重要的 pc.StandardInput.AutoFlush = true; outPut = pc.StandardOutput.ReadToEnd();//讀取結果 pc.WaitForExit(); pc.Close(); } }
1. 設置可變參數:必須在實參的最后一個;
2.循環執行dos命令
3. 必須 exit進行退出,不然會一直停留在dos,沒法返回信息;
補充:關於cmd命令執行中延時問題,由於對cmd延時的幾種方法(https://www.cnblogs.com/Platform/p/7137387.html)都看不順眼,而且用 timeout /t 5 /nobreak >nul 2>nul 或 waitfor TEST /t 5 >nul 2>nul 起不到作用,因為C#RunCMDCommand執行已經提前退出了。最后是考慮在cmd.txt中自定義一個命令加上毫秒或秒數:如sleep1, 當讀取到這條命令時,在C#的RunCMDCommand中處理為System.Threading.Thread.Sleep(1000); //毫秒來延時。
參考:https://blog.csdn.net/niuba123456/article/details/90509850
https://www.cnblogs.com/applebox/p/11612457.html