How do you determine if an Internet connection is available for your WinForms App?

前端 未结 8 803
生来不讨喜
生来不讨喜 2020-12-24 15:33

What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions

相关标签:
8条回答
  • 2020-12-24 16:18

    The following will determine if you are connected to a network, however, that doesn't necessarily mean that you are connected to the Internet:

    NetworkInterface.GetIsNetworkAvailable() 
    

    Here is a C# translation of Steve's code that seems to be pretty good:

    private static int ERROR_SUCCESS = 0;
    public static bool IsInternetConnected() {
        long dwConnectionFlags = 0;
        if (!InternetGetConnectedState(dwConnectionFlags, 0))
            return false;
    
        if(InternetAttemptConnect(0) != ERROR_SUCCESS)
            return false;
    
        return true;
    }
    
    
     [DllImport("wininet.dll", SetLastError=true)]
     public static extern int InternetAttemptConnect(uint res);
    
    
     [DllImport("wininet.dll", SetLastError=true)]
      public static extern bool InternetGetConnectedState(out int flags,int reserved); 
    
    0 讨论(0)
  • 2020-12-24 16:25

    A guess at Internet connectivity would be network availability, at NetworkInterface.GetIsNetworkAvailable(). The events on NetworkChange can tell you when it changes. Both classes are in the System.Net.NetworkInformation namespace.

    Of course, you won't know if the Internet is really available until you try to connect to something.

    0 讨论(0)
提交回复
热议问题