使用C#調用外部Ping命令獲取網絡連接情況
以前在玩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";
關閉Shell的使用
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");
從輸出流獲取命令執行結果,
在本機測試得到如下結果:
"Microsoft Windows 2000 [Version 5.00.2195]/r/n(C) 版權所有 1985-2000 Microsoft Corp./r/n/r/nD://himuraz//csharpproject//ZZ//ConsoleTest//bin//Debug>ping -n 1 192.192.132.231/r/n/r/r/nPinging 192.192.132.231 with 32 bytes of data:/r/r/n/r/r/nReply from 192.192.132.231: bytes=32 time<10ms TTL=128/r/r/n/r/r/nPing statistics for 192.192.132.231:/r/r/n??? Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),/r/r/nApproximate round trip times in milli-seconds:/r/r/n??? Minimum = 0ms, Maximum =?0ms, Average =?0ms/r/r/n/r/nD://himuraz//csharpproject//ZZ//ConsoleTest//bin//Debug>exit/r/n"
有了輸出結果,那還有什么好說的,分析strRst字符串就可以知道網絡的連接情況了。
完整代碼如下:
using System;
namespace ZZ
{
???? class ZZConsole
???? {
???????? [STAThread]
???????? static void Main(string[] args)
???????? {???
????????????? string ip = "192.192.132.229";
????????????? string strRst = CmdPing(ip);
????????????? Console.WriteLine(strRst);
????????????? Console.ReadLine();
???????? }
???????? private static string CmdPing(string strIp)
???????? {
????????????? 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 pingrst;
????????????? p.Start();
????????????? p.StandardInput.WriteLine("ping -n 1 "+strIp);
????????????? p.StandardInput.WriteLine("exit");
????????????? string strRst = p.StandardOutput.ReadToEnd();
????????????? if(strRst.IndexOf("(0% loss)")!=-1)
?????????????????? pingrst = "連接";
????????????? else if( strRst.IndexOf("Destination host unreachable.")!=-1)
?????????????????? pingrst = "無法到達目的主機";
????????????? else if(strRst.IndexOf("Request timed out.")!=-1)
?????????????????? pingrst = "超時";
????????????? else if(strRst.IndexOf("Unknown host")!=-1)
?????????????????? pingrst = "無法解析主機";
????????????? else
?????????????????? pingrst = strRst;
????????????? p.Close();
????????????? return pingrst;
???????? }
???? }
}
?