How to automatically logon to defined wi-fi using netsh in C#

43 Views Asked by At

I am currently using the netsh command-line tool to add a Wi-Fi profile and connect to a specified Wi-Fi network automatically when my program starts up.

But the issue is that I have to manually logon to it and type in the password...

public class WifiManager
{
    public void ConnectToWifi(string ssid, string psw)
    {
        // Create new profile
        Process.Start("netsh", $"wlan add profile filename=\"{CreateProfileXml(ssid, psw)}\"");

        // Use netsh to connect to the specified Wi-Fi network
        Process.Start("netsh", $"wlan connect name=\"{ssid}\"");
    }

    private string CreateProfileXml(string ssid, string psw)
    {
        // Create a Wi-Fi profile XML with the specified SSID and password
        return $@"<WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1"">
<name>{ssid}</name>
<SSIDConfig>
    <SSID>
        <name>{ssid}</name>
    </SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
    <security>
        <authEncryption>
            <authentication>WPA2PSK</authentication>
            <encryption>AES</encryption>
            <useOneX>false</useOneX>
        </authEncryption>
        <sharedKey>
            <keyType>passPhrase</keyType>
            <protected>false</protected>
            <keyMaterial>{psw}</keyMaterial>
        </sharedKey>
     </security>
   </MSM>
</WLANProfile>";
    }
}

------

private void MainForm_Load(object sender, EventArgs e)
{
    LoadSettings();
    UpdateWifiStatusLabel();

    string psw = ConfigurationManager.AppSettings["PswWifi"];
    string ssid = ConfigurationManager.AppSettings["Ssid"];

    if (autologon)
    {
         wifiManager.ConnectToWifi(ssid, psw);
    }
}
0

There are 0 best solutions below