VB.NET Use WebRequest to check if URI is valid
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?
Current开发者_Go百科ly 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.
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
HttpWebResponse response;
try
{
HttpWebRequest req;// Prepare request
response = req.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
HttpWebResponse exResponse = ex.Response as HttpWebResponse;
response = exResponse;
}
And now yo can just check responce.StatusCode
精彩评论