Listening for network availability changes in C#

Firstly a console application program to consecutively ENABLE and DISABLE the network connectivity:

using System;
using System.Diagnostics;

namespace NetworkDisconnect
{
   internal class Program
   {
      private static void Enable(string interfaceName)
      {
         var psi =
            new ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
         var p = new Process {StartInfo = psi};
         p.Start();
      }

      private static void Disable(string interfaceName)
      {
         var psi =
            new ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
         var p = new Process {StartInfo = psi};
         p.Start();
      }

      private static void Main(string[] args)
      {
         // Using 'netsh' Command, you can enable and disable “Local Area Connection”  
         while (true)
         {
            Enable("Local Area Connection");
            Console.WriteLine("Local connection ENABLED. Press key to DISABLE.");
            Console.ReadLine();
            Disable("Local Area Connection");
            Console.WriteLine("Local connection DISABLED. Press key to ENABLE.");
            Console.ReadLine();
         }         
      }
   }
}

Compile and run this program to alternately disable and re-enable your network availability by pressing any key. (The disabling will make unavailable any program that relies on a working network connection, such as email, Skype etc.)

You can also disable your network by pulling out your network cable or switching off your wifi, but it’s sometimes nice to demonstrate in this way as well.

And a console application to ‘listen’ for any changes in network availability that take place:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace NetworkConnectivity
{
   public class Program
   {
      public static void Main(string[] args)
      {
         NetworkChange.NetworkAvailabilityChanged +=
             new NetworkAvailabilityChangedEventHandler(OnNetworkAvailabilityChanged);

         Console.WriteLine("Listening for network availability changes. Press any key to exit.");
         Console.ReadLine();
      }

      static void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
      {
         if (e.IsAvailable)
         {
            Console.WriteLine("Network has become available");
         }
         else
         {
            Console.WriteLine("Network has become unavailable");
         }
      }
   }
}

By switching off the network connection, either programmatically or physically, the listener picks up on this fact and reports it accordingly:

And when re-establishing the connection, the program picks up on this as well:

Leave a Reply