以前玩 Windows 98 時,幾台電腦連起來測試網路連線是否正常,常用命令是 Ping.exe,感覺相當實用。
現在 .NET 為我們提供強大功能呼叫外部工具,並透過重導向輸入輸出獲取執行結果。下面用範例說明呼叫 Ping.exe 實現網路檢測,希望對 .NET 初學者有幫助。
首先使用 Process 類別建立獨立進程,匯入 System.Diagnostics:
using System.Diagnostics;
實例化 Process 類別,啟動獨立進程:
Process p = new Process();
Process 類別有 StartInfo 屬性,型別為 ProcessStartInfo,包含一些屬性與方法。用到幾個屬性:
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;以上屬性設定是關鍵步驟。設定好就啟動進程:
p.Start();
輸入要執行的命令,這裡是 ping:
p.StandardInput.WriteLine("ping -n 1 192.192.132.229");
p.StandardInput.WriteLine("exit");