1

What is the quickest and simplest way to check whether a file exists online?

I know how to check whether a file exists on my filesystem or whether a website exists but I don't know how to check whether a file exists online. How do I do this?

I would like to verify a link like the one below exists online:

http://ccc-itgs2012.wikispaces.com/file/view/AP+Human+Geography+Gapminder.flv

Santa
  • 103
  • 1
  • 3
  • 16

4 Answers4

1

You check online the same way you check on your file system: try to access the file, and handle the exception if the attempt fails (btw: if you're using File.Exists() on your file system, you're probably doing it wrong).

The only additional wrinkle is that, when checking online, you can send an http request for the resource and access the response stream without actually have to read through the stream, meaning you don't have to download the entire file just to know that the request will complete.

Community
  • 1
  • 1
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • That sounds awesome. Could you please give me an example. As when I've tried I could never get it to work – Santa Jan 25 '13 at 14:56
  • @Santa check this: http://stackoverflow.com/questions/2925692/vb-net-use-webrequest-to-check-if-uri-is-valid – WozzeC Jan 25 '13 at 15:09
  • Also Thanks Joel for pointing out the File.Exists thing, I was unaware of this. – WozzeC Jan 25 '13 at 15:11
  • Although that code worked. It took along time to execute (8-15 seconds) Is there a quicker method? as joel described it as though it would be really fast. – Santa Jan 25 '13 at 16:19
  • You just want to alter the method to return the response object. If you're looking at a boolean true/false, you're doing it wrong. It's unfortunately, but the only good way to check for volatile resources it to use them and handle the exception. – Joel Coehoorn Jan 25 '13 at 17:08
1

For HTTP, use the HTTP HEAD method. It behaves similar to the GET method except that it only returns the content headers. If the file doesn't exist, the server should return a 404 status code. Otherwise you can assume that the file exists (and even get its size from the content headers).

EDIT

You can use this code:

Public Function ResourceExists(location As Uri) As Boolean
    If (Not String.Equals(location.Scheme, Uri.UriSchemeHttp, StringComparison.InvariantCultureIgnoreCase)) And (Not String.Equals(location.Scheme, Uri.UriSchemeHttps, StringComparison.InvariantCultureIgnoreCase)) Then
        Throw New NotSupportedException("URI scheme is not supported")
    End If

    Dim request = Net.WebRequest.Create(location)
    request.Method = "HEAD"

    Try
        Using response = request.GetResponse
            Return DirectCast(response, Net.HttpWebResponse).StatusCode = Net.HttpStatusCode.OK
        End Using
    Catch ex As Net.WebException
        Select Case DirectCast(ex.Response, Net.HttpWebResponse).StatusCode
            Case Net.HttpStatusCode.NotFound
                Return False
            Case Else
                Throw
        End Select
    End Try
End Function

Usage:

Dim itExists As Boolean = ResourceExists(New Uri("http://ccc-itgs2012.wikispaces.com/file/view/AP+Human+Geography+Gapminder.flv"))

This does lock the caller's thread so you might want to refactor it into an async method.

Steven Liekens
  • 13,266
  • 8
  • 59
  • 85
0

This Code Work For Me

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
B.Habibzadeh
  • 490
  • 6
  • 10
0

The best way that i come up with and that actually found it working as wanted, because all the methods out there is just to check if the domain is found, so if the domain is found and the file is not, it will still tell you that the file is found, and my method is to try and download that file using DownloadFileAsync and run a timer for 3 second and after 3 second you check if any bytes were download from that file, if so, then this file is surly found through that link, if not, then it's not found, and then you can cancel the download and delete that file that has been created on you PC.

Here is a my code for that :

Imports System.IO
Imports System.Net
Public Class Form1
    Dim BytesReceived As Integer

    Public WithEvents Download As WebClient

    Private Sub DownloadBUT_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Download = New WebClient
        Download.DownloadFileAsync(New Uri("http://example.com/FileName.exe"), My.Computer.FileSystem.SpecialDirectories.Desktop & "FileName.exe")
        CheckFileTimer.Start()
        DownloadBUT.Enabled = False
    End Sub

    Private Sub Download_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles Download.DownloadProgressChanged
        BytesReceived = e.BytesReceived
    End Sub

    Private Sub CheckFileTimer_Tick(sender As Object, e As EventArgs) Handles CheckFileTimer.Tick
        CheckFileTimer.Stop()
        If BytesReceived = 0 Then
            MsgBox("File not found!")
        Else
            MsgBox("File found!")
        End If
        DownloadBUT.Enabled = True
        Download.CancelAsync()
        Try
            File.Delete(My.Computer.FileSystem.SpecialDirectories.Desktop & "FileName.exe")
        Catch ex As Exception : End Try
    End Sub
End Class

Hope this was useful to you :)

Mousa Alfhaily
  • 1,260
  • 3
  • 20
  • 38