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

后端 未结 7 1485
陌清茗
陌清茗 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:24

    In the end I used my own code:

    private bool CheckConnection(String URL)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Timeout = 5000;
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
            if (response.StatusCode == HttpStatusCode.OK)
                return true;
            else
                return false;
        }
        catch
        {
            return false;
        }
    }
    

    An interesting thing is that when the server is down (I turn off my Apache) I'm not getting any HTTP status, but an exception is thrown. But this works good enough :)

    0 讨论(0)
  • 2020-11-30 05:25

    You can try this;

    private bool CheckNet()
    {
        bool stats;
        if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
        {
            stats = true;
        }
        else
        {
            stats = false;
        }
        return stats;
    }
    
    0 讨论(0)
  • 2020-11-30 05:29

    I think this will be more accurate when it comes windows applications, Windows form or WPF apps, Instead of using WebClient or HttpWebRequest,

    public class InternetChecker
    {
        [System.Runtime.InteropServices.DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    
        //Creating a function that uses the API function...
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }
    
    }
    

    While calling write

    if(InternetCheckerCustom.CheckNet())
    {
      // Do Work 
    }
    else
    {
      // Show Error MeassgeBox 
    }
    
    0 讨论(0)
  • 2020-11-30 05:30

    Can we use ping just asking?

    try
    {
        System.Net.NetworkInformation.Ping ping = new Ping();
    
        PingReply result = ping.Send("www.google.com");
    
        if (result.Status == IPStatus.Success)
            return true;
         return false;
    }
    catch
    {
        return false;
    }
    
    0 讨论(0)
  • 2020-11-30 05:31

    Many developers are solving that "problem" just by ping-ing Google.com. Well...? :/ That will work in most (99%) cases, but how professional is to rely work of Your application on some external web service?

    Instead of pinging Google.com, there is an very interesting Windows API function called InternetGetConnectedState(), that recognizes whether You have access to Internet or not.

    THE SOLUTION for this situation is:

    using System;
    using System.Runtime;
    using System.Runtime.InteropServices;
     
    public class InternetAvailability
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int description, int reservedValue);
     
        public static bool IsInternetAvailable( )
        {
            int description;
            return InternetGetConnectedState(out description, 0);
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题