How to check whether you are connected to Internet or not in C#?

CsharpServer Side ProgrammingProgramming

There are many ways to check whether internet is connected to a machine in C# or not. Make use of System.Net namespace which provides common methods for sending data to and receiving data from a resource identified by a URI. The WebClient or HttpClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. Here in the below example we have used (OpenRead)Returns the data from a resource as a Stream.

Checks by hitting the url "http://google.com/generate_204" if success return true else false.

The below example runs in the loop and checks whether the internet is connected or not. If the Internet is connected return true or else return false.

Example

static void Main(string[] args){
   var keepRetrying = true;
   while (keepRetrying){
      if (IsConnectedToInternet()){
         keepRetrying = false;
         System.Console.WriteLine("Connected");
      } else {
         keepRetrying = true;
         System.Console.WriteLine("Not Connected");
      }
   }
}
public static bool IsConnectedToInternet(){
   try{
      using (var client = new WebClient())
      using (client.OpenRead("http://google.com/generate_204"))
      return true;
   }
   catch { }
   return false;
}

Output

Connected
raja
Published on 05-Nov-2020 18:05:45
Advertisements