如何获取上次使用的网络连接的名称?

时间:2012-01-03 00:06:34

标签: c# .net ras

我有一个设备(USB调制解调器)可以在计算机上安装很多网络连接,用户可以随时改变网络连接并随时可以断开连接。然后我需要使用最后一个网络连接,这可能吗?窗户保存在任何东西?

欢迎不同的解决方法。

1 个答案:

答案 0 :(得分:0)

我认为您无法获得“最后一次连接”,但您可以获得Active Connection,还可以通过来自Networking名称空间的事件检测“网络已断开连接/已连接”。

这是我之前使用的一些VB.Net代码,但您应该看到意图。

Dim networkAvailable As Boolean = Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
AddHandler System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged, AddressOf NetworkAddressChanged
AddHandler System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged, AddressOf NetworkAvailabilityChanged


Private Sub OutputNetworkAddresses(message As String, linePrefix As String)
    Dim adapters() As Net.NetworkInformation.NetworkInterface
    adapters = Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces
    For Each adapter As Net.NetworkInformation.NetworkInterface In adapters

        Dim properties As IPInterfaceProperties = adapter.GetIPProperties()
        For Each ipi As IPAddressInformation In properties.UnicastAddresses
            Dim ip As Net.IPAddress = ipi.Address
            If ip.IsIPv6LinkLocal Or ip.Equals(IPAddress.Any) Or ip.Equals(IPAddress.IPv6Any) Or IPAddress.IsLoopback(ip) Then
                'Debug.Print("IPv6=" & ip.ToString)
            Else
                Console.WriteLine(String.Format("{0} - {1}", linePrefix, ip.ToString()))
            End If
        Next
    Next
End Sub