VB.NET Use WebRequest to check if URI is valid

血红的双手。 提交于 2019-12-06 05:39:36

问题


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.


回答1:


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



回答2:


        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



来源:https://stackoverflow.com/questions/2925692/vb-net-use-webrequest-to-check-if-uri-is-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!