從輸出流獲取命令執行結果:
string strRst = p.StandardOutput.ReadToEnd();
本機測試結果如下:
"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;
using System.Diagnostics;
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;
}
}
}
總結:不僅是 Ping 命令,只要是命令列程式或 DOS 內部命令,都可用此方式執行並獲取結果,執行過程不會顯示,若需呼叫外部程式可嵌入使用。