平時我們的電腦會串連很多種網路類型:有線網、無線網、VPN。每種網路類型可能又包含不同的網路資源。在Windows 7 中儲存著所有使用者已串連過的網路資源。本篇將通過Windows API Code Pack 擷取這些網路資源的屬性及詳細資料。
首先建立一個項目,在其中引入WindowsAPICodePack.dll。開啟XAML代碼,添加<TabControl> 將所有的網路資源以標籤形式存放其中。
<Grid> <TabControl Margin="11,10,11,11" x:Name="tabControl" /></Grid>
在C#中加入using Microsoft.WindowsAPICodePack.Net 命名空間。編寫一個AddProperty() 方法,用來往Tab標籤裡添加網路屬性和資訊。
private void AddProperty(string propertyName, string propertyValue, StackPanel parent){ StackPanel panel = new StackPanel(); panel.Orientation = Orientation.Horizontal; Label propertyNameLabel = new Label(); propertyNameLabel.Content = propertyName; panel.Children.Add(propertyNameLabel); Label propertyValueLabel = new Label(); propertyValueLabel.Content = propertyValue; panel.Children.Add(propertyValueLabel); parent.Children.Add(panel);}
接下來編寫一個LoadNetworkConnections() 方法,用它來載入Windows 7 中儲存的網路資源。通過NetworkCollection 類可以獲得本機中所有網路資源資訊。利用NetworkConnectivityLevels 可以選擇All、Connected、Disconnected 三種不同的狀態模式。本例中我們選取所有的網路資源(All)。隨後遍曆這些網路資源,並建立相應的TabItem 標籤,將網路資源屬性通過上面建立的AddProperty() 方法添加到標籤。
private void LoadNetworkConnections(){ NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All); foreach (Network n in networks) { TabItem tabItem = new TabItem(); tabItem.Header = string.Format("Network {0} ({1})", tabControl.Items.Count, n.Name); tabControl.Items.Add(tabItem); StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Vertical; AddProperty("Name: ", n.Name, stackPanel); AddProperty("Description: ", n.Description, stackPanel); AddProperty("Domain type: ", n.DomainType.ToString(), stackPanel); AddProperty("Is connected: ", n.IsConnected.ToString(), stackPanel); AddProperty("Is connected to the internet: ", n.IsConnectedToInternet.ToString(), stackPanel); AddProperty("Network ID: ", n.NetworkId.ToString(), stackPanel); AddProperty("Category: ", n.Category.ToString(), stackPanel); AddProperty("Created time: ", n.CreatedTime.ToString(), stackPanel); AddProperty("Connected time: ", n.ConnectedTime.ToString(), stackPanel); AddProperty("Connectivity: ", n.Connectivity.ToString(), stackPanel); tabItem.Content = stackPanel; }}
最後,只需要在MainWindow() 加入LoadNetworkConnections() 方法即可。
public MainWindow(){ InitializeComponent(); LoadNetworkConnections();}
運行程式瀏覽下效果,本機所有網路資源的詳細資料都將顯示出來供使用者參考。
源碼下載
NetworkListMgr.zip