|
|
Title | Validate a URL in Visual Basic .NET |
Description | This example shows how to validate a URL in Visual Basic .NET. |
Keywords | validate URL, URL, VB.NET |
Categories | VB.NET, Utilities, Internet |
|
|
The UrlIsValid function creates an HttpWebRequest object and calls its GetResponse method to see if the URL points to a Web page. If it is successful, the function returns True.
Note that the Finally block closes the HttpWebResponse. If the code doesn't do this, your system may use up all of its connections and further requests get stuck. To see this, comment out the Close statement and use the program to validate several URLs.
|
|
Private Function UrlIsValid(ByVal url As String) As Boolean
Dim is_valid As Boolean = False
If url.ToLower().StartsWith("www.") Then url = _
"http://" & url
Dim web_response As HttpWebResponse = Nothing
Try
Dim web_request As HttpWebRequest = _
HttpWebRequest.Create(url)
web_response = _
DirectCast(web_request.GetResponse(), _
HttpWebResponse)
Return True
Catch ex As Exception
Return False
Finally
If Not (web_response Is Nothing) Then _
web_response.Close()
End Try
End Function
|
|
This example is based on the DevX tip Determine Whether a URL Is Valid. I have made some changes to simplify it and added the code to close the response.
|
|
|
|
|
|