Download the latest file from an FTP server

2020-02-01 06:34发布

问题:

I have to download the latest file from an FTP Server. I know how download the latest file from my computer, but I don't how download from an FTP server.

How can I download the latest file from a FTP Server?

This is my program to download the latest file from my Computer

public Form1()
    {
        InitializeComponent();

        string startFolder = @"C:\Users\user3\Desktop\Documentos XML";

        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);

        IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

        IEnumerable<System.IO.FileInfo> fileQuerry =
            from file in fileList
            where file.Extension == ".txt"
            orderby file.CreationTimeUtc
            select file;

        foreach (System.IO.FileInfo fi in fileQuerry)
            {
                var newestFile =
                (from file in fileQuerry
                 orderby file.CreationTimeUtc
                 select new { file.FullName, file.Name })
                 .First();
                textBox2.Text = newestFile.FullName;
            }
    }

OK, with this code I know the date of the last file, but How I know the name of this file????????

回答1:

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:

  • 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

    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. This method uses the LastModified property that you mention:

    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 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)