Download the latest file from an FTP server

女生的网名这么多〃 提交于 2019-11-28 00:32:49

You have to retrieve timestamps of remote files to select the latest one.

Unfortunately, there's no really reliable and efficient way to retrieve modification timestamps of all files in a directory 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:


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 SFTP, but translates to C# and 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!