Windows 10 IoT Core以编程方式删除WiFi配置文件



>我需要从代码中删除保存的wifi配置文件,以便再次启用SoftAP。根据ms文档,无法删除配置文件,只能断开连接。这不可能吗?

无线上网的女士文档https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifi.wifiadapter

设备门户 APIhttps://learn.microsoft.com/de-ch/windows/mixed-reality/device-portal-api-reference#wifi-management

这是我使用设备门户 API 断开与 wifi 连接的工作代码

        // API creds
        string username = "Administrator";
        string password = "p@ssw0rd
        // API request URIs
        string apiUri = "http://192.168.1.15:8080/api/wifi/network";
        // WiFi details
        string wifiInterface = string.Empty;
        string wifiProfile = string.Empty;
        // WiFi access
        WiFiAccessStatus wifiAccess = await WiFiAdapter.RequestAccessAsync();
        if (wifiAccess == WiFiAccessStatus.Allowed)
        {
            // Get WiFi adapter
            IReadOnlyList<WiFiAdapter> wifiAdapterResult = await WiFiAdapter.FindAllAdaptersAsync();
            WiFiAdapter wifiAdapter = wifiAdapterResult[0];
            // Get conn profile / details
            ConnectionProfile profile = await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync();
            wifiInterface = profile.NetworkAdapter.NetworkAdapterId.ToString();
            wifiProfile = profile.ProfileName;
        }
        // API creds
        PasswordCredential credentials = new PasswordCredential("login", username, password);
        // HttpClient filter
        HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
        filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;
        filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
        filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
        filter.ServerCredential = credentials;
        // HttpClient
        HttpClient client = new HttpClient(filter);
        apiUri = apiUri + "?interface=" + wifiInterface + "&op=disconnect" + "&createprofile=no";
        // Request
        HttpRequestMessage request = new HttpRequestMessage();
        request.Method = new HttpMethod("POST");
        request.RequestUri = new Uri(apiUri);
        // Send request
        try
        {
            // Response
            HttpResponseMessage response = await client.SendRequestAsync(request);
            // Again
            if (response.Content.ToString().Contains("Authorization Required"))
            {
                response = await client.SendRequestAsync(request);
            }
        }
        catch
        {
            // Dispose
            client.Dispose();
            filter.Dispose();
        }

但是要删除 wifi 配置文件,我从 API 找不到 404。根据上面链接的 API 文档,请求应该没问题。这是我删除wifi配置文件的代码

        // API creds
        string username = "Administrator";
        string password = "p@ssw0rd
        // API request URIs
        string apiUri = "http://192.168.1.15:8080/api/wifi/network";
        // WiFi details
        string wifiInterface = string.Empty;
        string wifiProfile = string.Empty;
        // WiFi access
        WiFiAccessStatus wifiAccess = await WiFiAdapter.RequestAccessAsync();
        if (wifiAccess == WiFiAccessStatus.Allowed)
        {
            // Get WiFi adapter
            IReadOnlyList<WiFiAdapter> wifiAdapterResult = await WiFiAdapter.FindAllAdaptersAsync();
            WiFiAdapter wifiAdapter = wifiAdapterResult[0];
            // Get conn profile / details
            ConnectionProfile profile = await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync();
            wifiInterface = profile.NetworkAdapter.NetworkAdapterId.ToString();
            wifiProfile = profile.ProfileName;
        }
        // API creds
        PasswordCredential credentials = new PasswordCredential("login", username, password);
        // HttpClient filter
        HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
        filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;
        filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
        filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
        filter.ServerCredential = credentials;
        // HttpClient
        HttpClient client = new HttpClient(filter);
        apiUri = apiUri + "?interface=" + wifiInterface + "&profile=" + wifiProfile;
        // Request
        HttpRequestMessage request = new HttpRequestMessage();
        request.Method = new HttpMethod("DELETE")
        request.RequestUri = new Uri(apiUri);
        // Send request
        try
        {
            // Response
            HttpResponseMessage response = await client.SendRequestAsync(request);
            // Again
            if (response.Content.ToString().Contains("Authorization Required"))
            {
                response = await client.SendRequestAsync(request);
            }
        }
        catch
        {
            // Dispose
            client.Dispose();
            filter.Dispose();
        }

编辑//

为了解决这个问题,从内部版本 17763 开始,有一种新方法可以直接从可用代码中删除 WiFi 配置文件

bool canDelete = wifiProfile.CanDelete;
if (canDelete)
{
     ConnectionProfileDeleteStatus deleteStatus = await wifiProfile.TryDeleteAsync();
}

您可以从程序中调用netsh

netsh wlan delete <profile name>应该带你去那里。

经过几个小时的尝试,终于找到了解决方案!对于那些感兴趣的人,您必须调用"运行命令"API,它允许您运行某些Windows命令

string deleteCommand = "netsh wlan delete profile name=*";
string cmdApi = string.Format("http://192.168.1.15:8080/api/iot/processmanagement/runcommand?command={0}&runasdefaultaccount={1}", GetBase64String(deleteCommand), GetBase64String("no"));

这里要注意的真正重要的事情是,您必须将命令编码为 base64 字符串,否则它将不起作用!

private string GetBase64String(string stringToConvert)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToConvert));
}

使用此代码,我终于可以删除某些wifi配置文件,或者在上面的示例中,删除每个保存的配置文件。

非常感谢安迪找到这个。我之前用命令行做过,但这确实有效。我围绕它添加了一些支持代码,以帮助遇到一些问题(例如获取、删除或发布(的其他人。如果它有效,那么我重新启动物联网以返回入职模式。也许有人会觉得这很有帮助。

可能需要也可能不需要以管理员身份登录门户,但这就是我的做法。if (interfaceGUID != null( 是由以前的 API 请求分配的,可以删除以进行测试。

private string password = "yourpassword";
private string localhost = "127.0.0.1";                              
private async Task DeleteProfile()
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                if (interfaceGUID != null)
                {
                    string deleteCommand = "netsh wlan delete profile name=*";
                    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://{0}:8080/api/iot/processmanagement/runcommand?command={1}&runasdefaultaccount={2}", localhost, Convert.ToBase64String(Encoding.UTF8.GetBytes(deleteCommand)), Convert.ToBase64String(Encoding.UTF8.GetBytes("no")))))
                    {
                        request.Headers.Authorization = CreateBasicCredentials("Administrator");
                        using (HttpResponseMessage response = await client.SendAsync(request))
                        {
                            if (response.IsSuccessStatusCode == true)
                            {
                                 ShutdownManager.BeginShutdown(Windows.System.ShutdownKind.Restart, TimeSpan.FromSeconds(1));
                            }
                            else
                            {
                                Debug.WriteLine("Could not delete the profiles. " + response.ReasonPhrase.ToString());
                            }
                        }
                    }
                }
                client.Dispose();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Could not delete the profiles. " + ex.InnerException.ToString());
        }
    }
private AuthenticationHeaderValue CreateBasicCredentials(string userName)
    {
        string toEncode = userName + ":" + password;
        Encoding encoding = Encoding.GetEncoding("iso-8859-1");
        byte[] toBase64 = encoding.GetBytes(toEncode);
        string parameter = Convert.ToBase64String(toBase64);
        return new AuthenticationHeaderValue("Basic", parameter);
    }

最近一直在研究Windows设备门户API,并遇到了这篇文章。 代码获得 404 响应的原因是,在 API URI 中,&profile=需要 Base64 值,而不是你正在使用的文本字符串。 将配置文件名称编码为 Base64 后,它应该可以工作。

我相信这在MS的设备门户文档中没有明确说明,因为我只是通过使用Web浏览器调试器在删除WIFI配置文件时检查Windows设备门户网页才发现这一点。

为了解决这个问题,从内部版本 17763 开始,有一种新方法可以直接从可用代码中删除 WiFi 配置文件

bool canDelete = wifiProfile.CanDelete;
if (canDelete)
{
     ConnectionProfileDeleteStatus deleteStatus = await wifiProfile.TryDeleteAsync();
}

最新更新