用Ping命令作示例,說明C#下執行命令行或DOS內部命令的一種方法,并獲取相應的結果。執行時可以讓這些程序的執行過程不顯示出來,調用外部程序就可以分析執行結果。
using System;
// 要用使用Process類來創建獨立的進程,導入
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類,啟動一個獨立進程
Process p = new Process();

// 設定程序名
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;

// 啟動進程
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;
// if end

p.Close();

return pingrst;
}
}
}
|