How to check if connected to internet in C#?

WBOY
Release: 2023-09-01 20:29:10
forward
1604 people have browsed it

How to check if connected to internet in C#?

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.

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; }
Copy after login

Output

Connected
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!