How to check the Internet connection with .NET, C#, and WPF

后端 未结 7 1503
陌清茗
陌清茗 2020-11-30 04:51

I am using .NET, C# and WPF, and I need to check whether the connection is opened to a certain URL, and I can\'t get any code to work that I have found on the Internet.

7条回答
  •  一向
    一向 (楼主)
    2020-11-30 05:37

    I went through all the solutions. NetworkInterface.GetIsNetworkAvailable() doesn't check internet connection. It only check whether any network connection is available.

    Ping is not reliable as in many network ping is turned off. Connecting to google with webclient is also not 100% reliable and it also has performance overhead if you use it too frequently.

    Using Windows NLM API seems a better solution to me.

    using NETWORKLIST;
    
    namespace Network.Helpers
    {
        public class InternetConnectionChecker
        {
            private readonly INetworkListManager _networkListManager;
    
            public InternetConnectionChecker()
            {
                _networkListManager = new NetworkListManager();
            }
    
            public bool IsConnected()
            {
                return _networkListManager.IsConnectedToInternet;
            }
            
        }
    }
    

    This is how to add it to project.

提交回复
热议问题