用Ping命令作示例,說明C#下執(zhí)行命令行或DOS內(nèi)部命令的一種方法,并獲取相應(yīng)的結(jié)果。執(zhí)行時可以讓這些程序的執(zhí)行過程不顯示出來,調(diào)用外部程序就可以分析執(zhí)行結(jié)果。
using System;
// 要用使用Process類來創(chuàng)建獨立的進(jìn)程,導(dǎo)入
using System.Diagnostics;

namespace Cmd
  {

class CmdConsole
 {

[STAThread]
static void Main(string[] args)
 {
Console.Write("Please Input IP Address: ");
string ip = Console.ReadLine();
string strRst = CmdPing(ip);
Console.WriteLine(strRst);
Console.ReadLine();
}

private static
string CmdPing(string strIp)
 {
// 實例一個Process類,啟動一個獨立進(jìn)程
Process p = new Process();

// 設(shè)定程序名
p.StartInfo.FileName = "cmd.exe";
// 關(guān)閉Shell的使用
p.StartInfo.UseShellExecute = false;
// 重定向標(biāo)準(zhǔn)輸入
p.StartInfo.RedirectStandardInput = true;
// 重定向標(biāo)準(zhǔn)輸出
p.StartInfo.RedirectStandardOutput = true;
//重定向錯誤輸出
p.StartInfo.RedirectStandardError = true;
// 設(shè)置不顯示窗口
p.StartInfo.CreateNoWindow = true;

// 啟動進(jìn)程
string pingrst;

p.Start();

p.StandardInput.WriteLine("ping -n 1 " + strIp);
p.StandardInput.WriteLine("exit");

// 從輸出流獲取命令執(zhí)行結(jié)果
string strRst = p.StandardOutput.ReadToEnd();

if (strRst.IndexOf("( 0% loss )") != -1)
pingrst = "連接";
else if (strRst.IndexOf("Destination host unreachable.") != -1)
pingrst = "無法到達(dá)目的主機(jī)";
else if (strRst.IndexOf("Request timed out.") != -1)
pingrst = "超時";
else if (strRst.IndexOf("Unknown host") != -1)
pingrst = "無法解析主機(jī)";
else
pingrst = strRst;
// if end

p.Close();

return pingrst;
}
}
}
|