Check if Internet connection is available using C#
There can be situations when you need to check, whether your application has Internet access.
Maybe you have to download/upload some file or database, or just run some application check.
Many developers are solving that "problem" just by ping-ing Google.com. Well...? :/
That will work in most (99%) cases, but how professional is to rely work of Your application on some external web service?
Instead of pinging Google.com, there is an very interesting Windows API function called InternetGetConnectedState(), that recognizes whether You have access to Internet or not.
THE SOLUTION for this situation is:
using System;
using System.Runtime;
using System.Runtime.InteropServices;
public class InternetAvailability
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int description, int reservedValue);
public static bool IsInternetAvailable( )
{
int description;
return InternetGetConnectedState(out description, 0);
}
}
And thats it!