Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用bing地图api处理windows 8应用程序中没有internet连接的问题_C#_Windows 8.1_Bing Maps_Internet Connection - Fatal编程技术网

C# 使用bing地图api处理windows 8应用程序中没有internet连接的问题

C# 使用bing地图api处理windows 8应用程序中没有internet连接的问题,c#,windows-8.1,bing-maps,internet-connection,C#,Windows 8.1,Bing Maps,Internet Connection,我正在使用C#中的Bing地图sdk创建一个Windows 8.1应用程序,使用本指南 现在,当我在没有互联网连接的情况下使用此应用程序时,应用程序崩溃。那么,我该如何处理这个无互联网连接例外情况呢?首先检查它 例如,通过方法: public static bool CheckForInternetConnection() { try { using (var client = new WebClient()) using (var stream

我正在使用C#中的Bing地图sdk创建一个Windows 8.1应用程序,使用本指南


现在,当我在没有互联网连接的情况下使用此应用程序时,应用程序崩溃。那么,我该如何处理这个无互联网连接例外情况呢?

首先检查它

例如,通过方法:

public static bool CheckForInternetConnection()
{
    try
    {
        using (var client = new WebClient())
        using (var stream = client.OpenRead("http://www.bing.com"))
        {
            return true;
        }
    }
    catch
    {
        return false;
    }
}

将此属性放入App.xaml.cs以测试Internet是否可用

public static bool IsInternetAvailable
{
    get
    {
        var profiles = NetworkInformation.GetConnectionProfiles();
        var internetProfile = NetworkInformation.GetInternetConnectionProfile();
        return profiles.Any(s => s.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess)
            || (internetProfile != null
                    && internetProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
    }
}

if(App.IsInternetAvailable)
{
    //Do operation of Bing map
}
else
{
    //Show message dialog
}

这是我的windows 8.1代码

public static bool have_net()
    {
        ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

        if (InternetConnectionProfile == null) return false;

        NetworkConnectivityLevel ncl = InternetConnectionProfile.GetNetworkConnectivityLevel();

        if (ncl == NetworkConnectivityLevel.InternetAccess)
        {
            return true;
        }

        bool b1 = InternetConnectionProfile.IsWwanConnectionProfile;
        bool b2 = InternetConnectionProfile.IsWlanConnectionProfile;

        return (b1 || b2);
    }

我想你的代码是针对windows phone的。但我的应用程序是针对windows 8.1 appAnd的,在该函数返回后,但在您的代码对结果进行任何处理之前,外部现实会发生变化。因此,您必须编写代码,即使在该函数返回true之后,也必须处理internet不可用(或通过使用它部分改变)的问题。鉴于您必须编写此代码才能生成健壮的软件,调用此函数有什么可能的好处?请参阅我对interneo的评论-可以对此属性提出相同的问题。“那么我如何处理此无互联网连接例外?”-与您处理程序无法控制的任何其他问题的方式相同-您必须在异常发生时捕获异常,然后决定是重新尝试您刚才尝试的还是放弃并告诉用户。目前的两个答案都是同样错误的,因为他们认为有可能“预先检查”某些东西,这些东西在任何时候都可以改变它的实际状态,而不受程序的控制。