How to check if a file exists on an FTP server

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
...
End If

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s