C# Check Remote Server

后端 未结 5 1857
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 06:18

Can anyone advise what the best way to check (using .NET 3.5) if a remote server is available?

I was thinking of using the following code but would like to know if

5条回答
  •  情书的邮戳
    2020-12-15 07:17

    just to add to Dan's answer... I just had to implement this and here is a nice little code snippet that should help out those that make it here from Google.

    Imports System.Net
    Private Function URLExists(pURL As String) As Boolean
    
        Try
            'Creating the HttpWebRequest
            Dim request As HttpWebRequest = TryCast(WebRequest.Create(pURL), HttpWebRequest)
            'Setting the Request method HEAD, you can also use GET too.
            request.Method = "HEAD"
            'Getting the Web Response.
            Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
            'Returns TURE if the Status code == 200
            Return (response.StatusCode = HttpStatusCode.OK)
        Catch
            'Any exception will returns false.
            Return False
        End Try
    End Function
    

    sorry it is VB but that is what I had in front of me. I will leave it as an exercise for the reader to convert this to C# as needed.

提交回复
热议问题