Unfortunately, there's no really reliable and efficient way to retrieve timestamps using features offered by .NET framework, as it does not support the FTP MLSD
command. The MLSD
command provides a listing of remote directory in a standardized machine-readable format. The command and the format is standardized by RFC 3659.
Alternatives you can use, that are supported by .NET framework:
ListDirectoryDetails
method (the FTP LIST
command) to retrieve details of all files in a directory and then you deal with FTP server specific format of the details (*nix format similar to the ls
*nix command is the most common, a drawback is that the format may change over time, as for newer files "May 8 17:48" format is used and for older files "Oct 18 2009" format is used).
DOS/Windows format: C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response
*nix format: Parsing FtpWebRequest ListDirectoryDetails line
GetDateTimestamp
method (the FTP MDTM
command) to individually retrieve timestamps for each file. An advantage is that the response is standardized by RFC 3659 to YYYYMMDDHHMMSS[.sss]
. A disadvantage is that you have to send a separate request for each file, what can be quite inefficient.
const string uri = "ftp://example.com/remote/path/file.txt";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("{0} {1}", uri, response.LastModified);
Alternatively you can use a 3rd party FTP client implementation that supports the modern MLSD
command.
For example WinSCP .NET assembly supports that.
There's even an example for your specific task: Downloading the most recent file.
The example is for PowerShell and the SFTP, but translates to C# and the FTP easily:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "username",
Password = "password",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Get list of files in the directory
string remotePath = "/remote/path/";
RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath);
// Select the most recent file
RemoteFileInfo latest =
directoryInfo.Files
.OrderByDescending(file => file.LastWriteTime)
.First();
// Download the selected file
string localPath = @"C:\local\path\";
string sourcePath = RemotePath.EscapeFileMask(remotePath + latest.Name);
session.GetFiles(sourcePath, localPath).Check();
}
(I'm the author of WinSCP)