Let us learn how to check Internet Connection using Console Application
Introduction
Few days back I had discussion with a friend on a requirement to send mail using console application so he wants to check the status of Internet Connection.
Objective
- Checking Internet Connection in Console application
Using the code
- Go to Visual Studio -> Create a New Project -> Console Application
- Then we will import a Namespace using system.net that will allow us to check if the data is received or not.
- We will create an Byte array and Create an Object of WebClient Class available in System.Net
- Now we will assign a URL to download the data in the form of bytes using the Download method of WebClient Class.
- If the received data is not null and if its length is greater than 0. Then we can say that there is an Active internet Connection or There is no connection available.
//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace Check_Internet_Connection
{
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
byte[] recieveddata = null;
try
{
// Here we are checking tthe no of bytes recived
recieveddata = client.DownloadData("http://www.dotnetfunda.com");
}
catch (Exception ex)
{
Console.WriteLine("Error " + ex.Message.ToString());
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.ReadLine();
}
if (recieveddata != null && recieveddata.Length > 0)
{
// If we recieve data we say connection is active
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Internet Connection Available");
Console.ReadLine();
}
else
{
// If we dont recieve data we say connection is not active
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Internet Connection not Available");
Console.ReadLine();
}
}
}
}
Ouput 1 :- Internet Connection Available
Now i will disable the connection and we will get Internet Connection Not available.
Output 2 :- No Internet Connection
Conclusion
Using this article as resource we can change the code as our logic if there are mails send out automatically and if while sending mail the connection fails we can capture the message and store it in LOG.