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.
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.
Using C# FtpWebRequest and FtpWebReponse, you can use the following recursion (make sure the folder strings terminate in '\'):
The "item.Contains('.')" is a bit primitive, but has worked for my purposes. Post a comment if you need an example of the methods:
or
For FTP protocol you can use
FtpWebRequest
class from .NET framework. Though it does not have any explicit support for recursive file operations (including downloads). You have to implement the recursion yourself:Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the
FtpWebRequest
. TheFtpWebRequest
unfortunately does not support theMLSD
command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.Your options are:
LIST
command =ListDirectoryDetails
method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by thed
at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)The
url
must be like:ftp://example.com/
orftp://example.com/path/
Or use 3rd party library that supports recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to
Session.GetFiles
:Internally, WinSCP uses the
MLSD
command, if supported by the server. If not, it uses theLIST
command and supports dozens of different listing formats.(I'm the author of WinSCP)
You can use FTPClient from laedit.net. It's under Apache license and easy to use.
It use FtpWebRequest :
WebRequestMethods.Ftp.ListDirectoryDetails
to get the detail of all the list of the folderWebRequestMethods.Ftp.DownloadFile
to download it to a local folderYou could use
System.Net.WebClient.DownloadFile()
, which supports FTP. MSDN Details heredownloading 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:
Decent third party FTP component should have a method for handling those issues. Following code uses our Rebex FTP for .NET.
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).