What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2061
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

27条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 08:19

    Use NetworkMonitor to monitoring network state and internet connection.

    Sample:

    namespace AmRoNetworkMonitor.Demo
    {
        using System;
    
        internal class Program
        {
            private static void Main()
            {
                NetworkMonitor.StateChanged += NetworkMonitor_StateChanged;
                NetworkMonitor.StartMonitor();
    
                Console.WriteLine("Press any key to stop monitoring.");
                Console.ReadKey();
                NetworkMonitor.StopMonitor();
    
                Console.WriteLine("Press any key to close program.");
                Console.ReadKey();
            }
    
            private static void NetworkMonitor_StateChanged(object sender, StateChangeEventArgs e)
            {
                Console.WriteLine(e.IsAvailable ? "Is Available" : "Is Not Available");
            }
        }
    }
    

提交回复
热议问题