Skip to content

Instantly share code, notes, and snippets.

@yemrekeskin
Created March 5, 2015 07:35
Show Gist options
  • Save yemrekeskin/df052c9a464cb0c9a4e2 to your computer and use it in GitHub Desktop.
Save yemrekeskin/df052c9a464cb0c9a4e2 to your computer and use it in GitHub Desktop.
Check Internet Connection with c#
class Program
{
static void Main(string[] args)
{
if(CheckInternetConnection())
Console.WriteLine("Internet var");
else Console.WriteLine("Internet yok");
Console.ReadLine();
}
public static bool CheckInternetConnection()
{
try
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://www.google.com"))
{
return true;
}
}
catch
{
return false;
}
}
}
@Biyuktul
Copy link

Biyuktul commented Jan 4, 2024

when i try this it says Webclient is deprecated
what is the alternative way to check internet conectivity in .net6 and above?

@syntax-tm
Copy link

@Biyuktul Yes, use HttpClient instead.

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, "https://google.com");
using var response = client.Send(request);

I'm on mobile and just going off of memory for the class names but that should be pretty close.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment