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
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);
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.