![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check whether you are connected to Internet or not in C#?
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
Advertisements