Click here to Skip to main content
15,880,503 members
Articles / Programming Languages / Visual Basic
Tip/Trick

How to check if a file exists on an FTP server

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
1 Mar 2011CPOL 98K   13   5
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)


Written By
Software Developer (Senior)
United States United States
Software Developer

Comments and Discussions

 
GeneralExcellent Pin
Samarjeet Singh8-Mar-13 6:04
Samarjeet Singh8-Mar-13 6:04 
GeneralC# Version of above code : public bool CheckIfFtpFileExists... Pin
Pravin Patil, Mumbai1-Mar-11 21:33
Pravin Patil, Mumbai1-Mar-11 21:33 
GeneralReason for my vote of 5 Interesting solution. I would sugges... Pin
DrABELL1-Mar-11 9:59
DrABELL1-Mar-11 9:59 
GeneralDoes not work Pin
us47118-Mar-11 1:23
us47118-Mar-11 1:23 
GeneralRe: Does not work Pin
Francis Lamarre19-Jan-12 8:24
Francis Lamarre19-Jan-12 8:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.