平时我们的计算机会连接很多种网络类型:有线网、无线网、×××。每种网络类型可能又包含不同的网络资源。在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();  }

运行程序浏览下效果,本机所有网络资源的详细信息都将显示出来供用户参考。

networklist

×××

NetworkListMgr.zip