In C#, there are many ways to check if the internet is connected to the computer. Leveraging the System.Net namespace, it provides common methods for sending data to and receiving data from the resource identified by the 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. In the example below, we use (OpenRead) to return data from a resource in a stream.
Check by clicking on the url "http://google.com/generate_204" and return true if successful otherwise false.
The example below runs in a loop and checks if the internet connected. Returns true if the internet is connected, false otherwise.
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; }
Connected
The above is the detailed content of How to check if connected to internet in C#?. For more information, please follow other related articles on the PHP Chinese website!