Search code examples
c#performancetimetimernetwork-connection

Measure internet connection loss time in C#


I want to check whether my internet connection is lost while my application is running and to measure the duration of any loss. For that I'm using the code below:

try
        {
            using (var client = new WebClient())
            using (var stream = client.OpenRead("http://www.google.com"))
            {
                //Doing something when connection running
            }
        }
        catch
        {
            //Doing something when connection lost
        }

Does anyone know how to write a log file using this code to measure my connection lost time (format: day:min:sec)?


Solution

  • You can check the internet connectivity using

    System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
    

    If you want to measure the time loss then you can include timer control in your project

    timer1.Enabled=true;
    timer1.Interval=1000;
    int count=0;
    
    private void timer1_tick(object sender,Eventargs e)
    {
        if(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()==false)
        {
            count++;
        }
    }
    

    This count will return you the time loss in seconds.