ManagedNativeWifi
ManagedNativeWifi copied to clipboard
ConnectNetworkAsync fails when not logged in locally or via RDP
I have an application that runs in the background. Typically, it is started through an RDP connection, but eventually we will run as a service. Everything works fine when we are still logged in, but if we start running and then disconnect from RDP, we get an exception on ConnectNetworkAsync:
System.ComponentModel.Win32Exception: 'MethodName: WlanConnect, ErrorCode: 87, ErrorMessage: The parameter is incorrect. '
The following code should help to reproduce the issue:
// give time to log out to trigger the issue
Thread.Sleep(10000);
// create profile
ManagedNativeWifi.NativeWifi.SetProfile(iface.Id, ProfileType.PerUser, CreateProfileXml(ssid+"_test", ssid, passwd), null, true);
// the following line works correctly while logged in, but throws an exception when logged out
bool connect_success = ManagedNativeWifi.NativeWifi.ConnectNetworkAsync(iface.Id, ssid + "_test", BssType.Infrastructure, new System.Net.NetworkInformation.PhysicalAddress(Array.ConvertAll(bssid.Split(':'), x => Convert.ToByte(x, 16))), new TimeSpan(0, 1, 0), new CancellationToken()).GetAwaiter().GetResult();
// ... snip ...
private static string CreateProfileXml(string profileName, string ssidString, string password) =>
$@"<?xml version=""1.0""?>
<WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1"">
<name>{profileName}</name>
<SSIDConfig>
<SSID>
<hex>{toHex(ssidString)}</hex>
<name>{ssidString}</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>manual</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>{password}</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>";