這篇文章主要介紹C#如何實現執行CMD命令并接收返回結果,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
最近工作的時候發現軟件里面通過查詢ARP表查詢某一IP對應的ARP條目的時,概率性出現查詢到的ARP條目為空,一開始懷疑Ping通但是沒有學習到ARP,
后來想想這是不可能的,最后經過各種分析發現是軟件中調用清除ARP的操作是通過調用Kernel.dll中的WinExec實現的,這個函數只要調用成功即返回,并不會等待調用的程序執行完畢才返回,
所以在某些反應遲鈍的電腦上,就會出現:如果你的操作順序是清除ARP,Ping,查詢ARP,就可能出現在Ping完后ARP表被清除掉,導致查不到ARP條目。
在網上查詢C#調用程序并等待程序執行完畢才返回的實現方法如下:
using System.Diagnostics;
Process CmdProcess = new Process(); CmdProcess.StartInfo.FileName = "cmd.exe";
CmdProcess.StartInfo.CreateNoWindow = true; // 不創建新窗口 CmdProcess.StartInfo.UseShellExecute = false; //不啟用shell啟動進程 CmdProcess.StartInfo.RedirectStandardInput = true; // 重定向輸入 CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向標準輸出 CmdProcess.StartInfo.RedirectStandardError = true; // 重定向錯誤輸出
方法一
CmdProcess.StartInfo.Arguments = "/c " + "=====cmd命令======";//“/C”表示執行完命令后馬上退出 CmdProcess.Start();//執行 CmdProcess.StandardOutput.ReadToEnd();//獲取返回值 CmdProcess.WaitForExit();//等待程序執行完退出進程 CmdProcess.Close();//結束
方法二
CmdProcess.StandardInput.WriteLine(str + "&exit"); //向cmd窗口發送輸入信息 CmdProcess.StandardInput.AutoFlush = true; //提交 CmdProcess.Start();//執行 CmdProcess.StandardOutput.ReadToEnd();//輸出 CmdProcess.WaitForExit();//等待程序執行完退出進程 CmdProcess.Close();//結束
首先 引入
using System.IO; StreamReader sr =CmdProcess.StandardOutput;//獲取返回值 string line = ""; int num = 1; while ((line=sr.ReadLine())!=null) { if(line!="") { Console.WriteLine(line + " " + num++); } }
//等待程序執行完退出進程 CmdProcess.WaitForExit(); //判斷程序是退出了進程 退出為true(上面的退出方法執行完后,HasExited的返回值為 true) falg = CmdProcess.HasExited;
補充:C# 動態調用exe可執行程序并接受返回值
static void Main(string[] args) { object output; try { using (Process p = new Process()) { p.StartInfo.FileName = @"ConsoleApp2.exe";//可執行程序路徑 p.StartInfo.Arguments = "";//參數以空格分隔,如果某個參數為空,可以傳入"" p.StartInfo.UseShellExecute = false;//是否使用操作系統shell啟動 p.StartInfo.CreateNoWindow = true;//不顯示程序窗口 p.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息 p.StartInfo.RedirectStandardInput = true; //接受來自調用程序的輸入信息 p.StartInfo.RedirectStandardError = true; //重定向標準錯誤輸出 p.Start(); p.WaitForExit(); //正常運行結束放回代碼為0 if (p.ExitCode != 0) { output = p.StandardError.ReadToEnd(); output = output.ToString().Replace(System.Environment.NewLine, string.Empty); output = output.ToString().Replace("\n", string.Empty); throw new Exception(output.ToString()); } else { output = p.StandardOutput.ReadToEnd(); } } Console.WriteLine(output); } catch (Exception ee) { Console.WriteLine(ee.Message); } Console.ReadKey(); }
以上是“C#如何實現執行CMD命令并接收返回結果”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。