Downloading directory from FTP server

Pavel Rabinovych picture Pavel Rabinovych · Apr 18, 2014 · Viewed 13k times · Source

I am developing FTP client by RAD Studio (IdFTP). How I can dowload directory from server? Delphi or C++. Thanks.

Answer

Remy Lebeau picture Remy Lebeau · Apr 18, 2014

You need to call TIdFTP.ChangeDir() to go to the desired starting directory, then call TIdFTP.List() to retrieve the names of its files and subdirectories, then loop through the TIdFTP.DirectoryListing calling TIdFTP.Get() on each filename and store each subdirectory name into your own local list, then finally repeat the above steps on each subdirectory in your local list.

For example:

Procedure DownloadFolder(ARemoteFolder, ALocalFolder: string);
Var
  SubFolders: TStringList;
  I: Integer;
Begin
  ALocalFolder := IncludeTrailingPathDelimiter(ALocalFolder);
  ForceDirectories(ALocalFolder);
  SubFolders := TStringList.Create;
  Try
    FTP.ChangeDir(ARemoteFolder);
    FTP.List;
    For I := 0 to FTP.DirectoryListing.Count-1 do
    Begin
      If FTP.DirectoryListing[I].ItemType = ditFile then
      Begin
        FTP.Get(FTP.DirectoryListing[I].FileName, ALocalFolder + FTP.DirectoryListing[I].FileName);
      End
      Else if FTP.DirectoryListing[I].ItemType = ditDirectory then
      Begin
        if (FTP.DirectoryListing[I].FileName <> '.') and FTP.DirectoryListing[I].FileName <> '..') then
          SubFolders.Add(FTP.DirectoryListing[I].FileName);
      End;     
    End;
    For I := 0 to SubFolders.Count-1 do
    Begin
      DownloadFolder(ARemoteFolder + '/' + SubFolders[I], ALocalFolder + SubFolders[I]);
    End;
  Finally
    SubFolders.Free;
  End;
End;

DownloadFolder('/StartingDir', 'C:\Downloaded');