Tuesday, April 2, 2013

Check Internet Connection availability in ASP. Net

Here I will show you a simple tip for checking internet connection availability in ASP.Net using C#.

In my previous posts, I explained SQL Server Database BackUp using C#, Partial Methods, Contextual Keyword, C# Static Methods and some other articles related to C#, ASP.Net and SQL Server .

To check the internet connection availability in ASP.Net using C# , you have to write the following code-

using System;
using System.Linq;
using System.Net;

namespace CheckNetConnection
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckInternetConnection();
        }
        public static void CheckInternetConnection()
        {
            HttpWebRequest objReq ;
            HttpWebResponse objRes ;
            try
            {
                objReq = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
                objRes = (HttpWebResponse)objReq.GetResponse();
                if (objRes.StatusCode == HttpStatusCode.OK)
                {
                    Console.WriteLine("Congrats ! Internet Connection is Available.");
                }
                else
                {
                    Console.WriteLine("Sorry ! Internet Connection is not Available.");
                }
                Console.ReadKey();

            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }
    }
}

Internet Connection
I hope you enjoyed this tip. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

^ Scroll to Top