【问题标题】:Windows 10 IoT Core remove WiFi profile programaticallyWindows 10 IoT Core 以编程方式删除 WiFi 配置文件
【发布时间】:2018-09-23 10:21:41
【问题描述】:

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

用于 wifi 的女士文档 https://docs.microsoft.com/en-us/uwp/api/windows.devices.wifi.wifiadapter

设备门户 API https://docs.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();
        }

编辑//

为了解决这个问题,自 build 17763 以来,有一种新方法可以直接从可用代码中删除 WiFi 配置文件

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

【问题讨论】:

  • 首先,您需要向我们展示一些代码,其中包含您尝试执行的操作以及结果。另外,您能否参考您提到的MS文章。完全有可能无法通过代码删除配置文件,但通常总有办法做某事。你只需要投入一些时间和反复试验
  • 我添加了一个指向 ms 文档的链接以进行 wifi 控制。没有这样的删除配置文件的方法。我没有要显示的代码,因为我还没有找到类似的东西。
  • 你也可以给我们看看你的代码吗
  • 目前我没有代码,因为我找不到任何 API 或删除 wifi 配置文件的方法。我发现的唯一东西是 Windows Device Portal API,但没有示例,所以我不知道如何使用。我已经编辑了问题的链接。
  • 不幸的是,我们没有任何东西可以处理您想要的东西,我们无能为力。如果您有一些关于如何将其拉入的代码示例,并试图移除设备,我们可能会做一些事情来帮助您。

标签: c# uwp win-universal-app raspberry-pi3 windows-10-iot-core


【解决方案1】:

您可以从您的程序中调用netsh

netsh wlan delete &lt;profile name&gt; 应该可以带你到那里。

【讨论】:

  • 据我所知,这是否需要添加一个注册密钥,所以这对我来说是没有选择的。
  • 添加 reg 键有什么用?产生一个进程?我不这么认为。 System.Diagnostics.Process.Start() 将为您启动netsh
  • 我在 msdn 论坛上从一个用户那里读到,它需要添加一个 reg 密钥来启动系统命令。使用 devive 门户 api,它可以完美运行。
【解决方案2】:

尝试了几个小时,终于找到了解决办法!有兴趣的可以调用“运行命令”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 配置文件,或者在上面的示例中,删除每个保存的配置文件。

【讨论】:

    【解决方案3】:

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

    以管理员身份登录门户可能需要也可能不需要,但我就是这样做的。 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);
        }
    

    【讨论】:

    • 很高兴它有帮助:)
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

      为了解决这个问题,自 build 17763 以来,有一种新方法可以直接从可用代码中删除 WiFi 配置文件

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多