VB.NET Use WebRequest to check if URI is valid

Robbo picture Robbo · May 28, 2010 · Viewed 15.5k times · Source

Looking for the best way to determine if a URI exists in VB.NET without downloading the actual content. System.IO.FileExists/My.Computer.FileSystem.FileExists can be used locally to determine if a file exists, is there an equivalent for the Web?

Currently I am using a HttpWebRequest to check URI existance using the ResponseStream. This populates the stream if the target does exist and throws an exception if it doesn't. The function is being expanded to also check for PDF files (typically 5MB +), images, etc and it will be a waste of time/bandwidth to actually populate the content into a stream.

In the case of "Success" (the target does exist) I do not wish to download the file or page, simply to end up with a Boolean which indicates the whether something exists at the end of this URI.

Answer

NoAlias picture NoAlias · May 28, 2010

Here it is in VB.NET. Make sure that your addresses start with http:// or https://.

Public Function CheckAddress(ByVal URL As String) As Boolean
    Try
        Dim request As WebRequest = WebRequest.Create(URL)
        Dim response As WebResponse = request.GetResponse()
    Catch ex As Exception
        Return False
    End Try
    Return True
End Function