首页 > 解决方案 > C# - 使用 WiFiAdapter.ConnectAsync 方法连接到特定接入点是不可靠的

问题描述

当使用 Windows.Devices.WiFi 命名空间中的 WiFiAdapter.ConnectAsync 方法并尝试连接到通过 WiFiAdapter.ScanAsync 方法检索到的特定 wifi 接入点时,它并不总是连接到通过 WiFiAvailableNetwork 类枚举的接入点。相反,它通常以最佳连接方式连接到接入点。

private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
            if (selectedNetwork == null || firstAdapter == null)
            {
                rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
                return;
            }
            WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
            if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
            {
                reconnectionKind = WiFiReconnectionKind.Automatic;
            }

            WiFiConnectionResult result;
            if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
                selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
            {
                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
            }
            else
            {
                // Only the password portion of the credential need to be supplied
                var credential = new PasswordCredential();

                // Make sure Credential.Password property is not set to an empty string. 
                // Otherwise, a System.ArgumentException will be thrown.
                // The default empty password string will still be passed to the ConnectAsync method,
                // which should return an "InvalidCredential" error
                if (!string.IsNullOrEmpty(NetworkKey.Password))
                {
                    credential.Password = NetworkKey.Password;
                }

                result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
            }

            if (result.ConnectionStatus == WiFiConnectionStatus.Success)
            {
                rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
            }
        }

我希望能够使用被传递给 ConnectAsync() 方法的关联 WiFiAvailableNetwork 类中的 BSSID 连接到 wifi 接入点。

标签: c#asynchronousuwpconnectionwifi

解决方案


推荐阅读