How can I implement a FileSystemWatcher
for an FTP location (in C#). The idea is whenever anything gets added in the FTP location I wish to copy it to my local machine. Any ideas will be helpful.
This is a follow up of my previous question Selective FTP download using .NET.
You cannot use the
FileSystemWatcher
or any other way, because the FTP protocol does not have any API to notify a client about changes in the remote directory.All you can do is to periodically iterate the remote tree and find changes.
It's actually rather easy to implement, if you use an FTP client library that supports recursive listing of a remote tree. Unfortunately, the built-in .NET FTP client, the
FtpWebRequest
does not. But for example with WinSCP .NET assembly version 5.9 (or newer), you can use theSession.EnumerateRemoteFiles
method.See the article Watching for changes in SFTP/FTP server:
(I'm the author of WinSCP)
Though, if you actually want to just download the changes, it's a way easier. Just use the
Session.SynchronizeDirectories
in the loop.If you do not want to use a 3rd party library, you have to do with limitations of the
FtpWebRequest
. For an example how to recursively list a remote directory tree with theFtpWebRequest
, see my answer to C# Download all files and subdirectories through FTP.