首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

使用 C# 呼叫外部 Ping 命令取得網路連線狀態(一)

     編輯:關於C語言

以前玩 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");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved