Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.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# 如何确定internet连接是否可用?_C#_Windows Runtime_Windows Store Apps - Fatal编程技术网

C# 如何确定internet连接是否可用?

C# 如何确定internet连接是否可用?,c#,windows-runtime,windows-store-apps,C#,Windows Runtime,Windows Store Apps,如何确定windows应用商店应用程序中是否有可用的internet连接?您可以使用来检测该连接;此示例代码添加了一个事件处理程序,每次连接状态更改时都会调用它 NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes static void NetworkInformation_NetworkStatusC

如何确定windows应用商店应用程序中是否有可用的internet连接?

您可以使用来检测该连接;此示例代码添加了一个事件处理程序,每次连接状态更改时都会调用它

NetworkInformation.NetworkStatusChanged += 
    NetworkInformation_NetworkStatusChanged; // Listen to connectivity changes

static void NetworkInformation_NetworkStatusChanged(object sender)
{
    ConnectionProfile profile = 
        NetworkInformation.GetInternetConnectionProfile();

    if ((profile != null) && profile.GetNetworkConnectivityLevel() >=
                NetworkConnectivityLevel.InternetAccess)
    {
        // We have Internet, all is golden
    }
}

当然,如果您只想检测它一次,而不想在它发生变化时得到通知,您可以从上面执行检查,而不必监听变化事件。

刚刚编写了异步函数来实现这一点:

    private void myPingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        if (e.Cancelled)
            return;

        if (e.Error != null)
            return;

        if (e.Reply.Status == IPStatus.Success)
        {
            //ok connected to internet, do something
        }
    }

    private void checkInternet()
    {
        Ping myPing = new Ping();
        myPing.PingCompleted += new PingCompletedEventHandler(myPingCompletedCallback);
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions options = new PingOptions(64, true);
        try
        {
            myPing.SendAsync("google.com", timeout, buffer, options);
        }
        catch
        {
        }
    }

还要注意的是,在检测网络状态方面,您可以更进一步:这里列出的ConstrainedInternetAccess可能会提供“一些”级别的访问:正如@Cabuxa.Mapache所指出的,这个答案不检查配置文件!=NULL,每当连接不可用时都会发生这种情况。请考虑在代码中添加一些上下文来解释为什么您的答案回答OP的问题。绝对是性能杀手…而且代码使用Ping类,这对Windows应用商店应用程序不可用,问题就在于此。
using Windows.Networking.Connectivity;      

public static bool IsInternetConnected()
{
    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    bool internet = (connections != null) && 
        (connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess);
            return internet;
}