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

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

提交回复
热议问题