65.9K
CodeProject is changing. Read more.
Home

How to check if a file exists on an FTP server

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Mar 1, 2011

CPOL
viewsIcon

99630

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