2

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

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

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
garci
  • 87
  • 3
  • 8

1 Answers1

4

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";
    session.GetFileToDirectory(latest.FullName, localPath);
}

(I'm the author of WinSCP)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992