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 if the user is not connected to the Internet.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With