Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

How to check if a file exists on an FTP server

5.00/5 (7 votes)
1 Mar 2011CPOL 99.6K  
Describes how to check for file existence on an FTP Server using VB.NET
This is a method that I’ve used in the past to check for file existence on an FTP server.

Public Function CheckIfFtpFileExists(ByVal fileUri As String) As Boolean
       Dim request As FtpWebRequest = WebRequest.Create(fileUri)
       request.Credentials = New NetworkCredential("username", "password")
       request.Method = WebRequestMethods.Ftp.GetFileSize
          Try
           Dim response As FtpWebResponse = request.GetResponse()
           ' THE FILE EXISTS
       Catch ex As WebException
            Dim response As FtpWebResponse = ex.Response
            If FtpStatusCode.ActionNotTakenFileUnavailable = response.StatusCode Then
                ' THE FILE DOES NOT EXIST
                Return False
            End If
        End Try
        Return True
    End Function


Get’s called like this:

If CheckIfFtpFileExists("ftp://ftp.domain.com/filename.txt") Then
        ' Do something
End If

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)