How to detect working internet connection in C#?

Detariael picture Detariael · Mar 26, 2010 · Viewed 33.8k times · Source

I have a C# code that basically uploads a file via FTP protocol (using FtpWebRequest). I'd like, however, to first determine whether there is a working internet connection before trying to upload the file (since, if there isn't there is no point in trying, the software should just sleep for a time and check again).

Is there an easy way to do it or should I just try to upload the file and in case it failed just try again, assuming the network connection was down?

Answer

Zyo picture Zyo · Sep 29, 2011

Just use the plain function

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

that return true of false if the connection is up.

From MSDN: A network connection is considered to be available if any network interface is marked "up" and is not a loopback or tunnel interface.

Keep in mind connectivity is not all, you can be connected to a local network and the router is not connected to the Internet for instance. To really know if you are connected to the internet try the Ping class.