bircastri
bircastri

Reputation: 2167

How can download file from FTP server with some extension in VisualBasic

I want to download the some file on remote location from FTP protocol, that have any extentions. For example I want to download the all file from remote site *.pdf, *.txt . So I have build this code in Visual Basic.

Public Function GetFiles() As Generic.List(Of String)
Dim fileList As New Generic.List(Of String)

Select Case _config.Protocol
    Case FTPConfiguration.FTPProtocol.FTP

    Dim objFTPRequest As FtpWebRequest = CType(FtpWebRequest.Create(New Uri(_config.FTPUrl & _config.MonitorDirectory)), FtpWebRequest)
    objFTPRequest.Credentials = New NetworkCredential(_config.FTPUsername, _config.FTPPassword)
    objFTPRequest.KeepAlive = False
    objFTPRequest.UsePassive = False
    objFTPRequest.UseBinary = True
    objFTPRequest.Method = WebRequestMethods.Ftp.ListDirectory



    Dim response As FtpWebResponse = CType(objFTPRequest.GetResponse(), FtpWebResponse)
    Using respStream As StreamReader = New StreamReader(objFTPRequest.GetResponse().GetResponseStream())
        Dim line As String = respStream.ReadLine()
        While line IsNot Nothing

        If line Like _config.FileSearch Then
            fileList.Add(line)

        End If

        line = respStream.ReadLine()
        End While
    End Using

End Select

For Each fileName As String In fileList
    Me.DownloadFile(fileName)
Next

Return fileList
End Function

How you can see, I have write this line to find the File but not works:

If line Like _config.FileSearch Then

I use LIKE operator but I think that this is not the corret way to fixed my problem.

Upvotes: 0

Views: 235

Answers (1)

Ashish Emmanuel
Ashish Emmanuel

Reputation: 728

You could use line.EndsWith(".pdf") to check if the file ends with that extension.

If you want to use like, the _config.FileSearch must be "*.pdf".

If line Like "*.pdf" Then
   Console.WriteLine(line)   
End If

You can also use Regular Expressions.

If Regex.IsMatch(line, "^.*\.(pdf|doc|txt|zip)$", RegexOptions.IgnoreCase) Then
   Console.WriteLine(line)
End If

Refer String.EndsWith and Like

Upvotes: 1

Related Questions