tags:

views:

1769

answers:

4

Hello.

What is the best way to download all files in a remote directory using C# and FTP and save them to a local directory?

thanks

+1  A: 

Hi,

downloading all files in a specific folder seems to be an easy task. However, there are some issues which has to be solved. To name a few:

  • How to get list of files (System.Net.FtpWebRequest gives you unparsed list and directory list format is not standardized in any RFC)
  • What if remote directory has both files and subdirectories. Do we have to dive into the subdirs and download it's content?
  • What if some of the remote files already exist on the local computer? Should they be overwritten? Skipped? Should we overwrite older files only?
  • What if the local file is not writable? Should the whole transfer fail? Should we skip the file and continue to the next?
  • How to handle files on a remote disk which are unreadable because we don’t have sufficient access rights?
  • How are the symlinks, hard links and junction points handled? Links can easily be used to create an infinite recursive directory tree structure. Consider folder A with subfolder B which in fact is not the real folder but the *nix hard link pointing back to folder A. The naive approach will end in an application which never ends (at least if nobody manage to pull the plug).

Decent third party FTP component should have a method for handling those issues. Following code uses our Rebex FTP for .NET.

using (Ftp client = new Ftp())
        {
            // connect and login to the FTP site
            client.Connect("mirror.aarnet.edu.au");
            client.Login("anonymous", "my@password");

            // download all files
            client.GetFiles(
                "/pub/fedora/linux/development/i386/os/EFI/*",
                "c:\\temp\\download",
                FtpBatchTransferOptions.Recursive,
                FtpActionOnExistingFiles.OverwriteAll
            );

            client.Disconnect();
        }

The code is taken from my blogpost available at blog.rebex.net. The blogpost also references a sample which shows how ask the user how to handle each problem (e.g. Overwrite/Overwrite older/Skip/Skip all).

Martin Vobr
+1  A: 

You can use FTPClient from laedit.net. It's under Apache license and easy to use.

Jérémie Bertrand
+1  A: 

You could use System.Net.WebClient.DownloadFile(), which supports FTP. MSDN Details here

STW