【问题标题】:Download the latest file from an FTP server从 FTP 服务器下载最新文件
【发布时间】:2015-07-27 08:24:41
【问题描述】:

我必须从 FTP 服务器下载最新的文件。我知道如何从我的电脑下载最新的文件,但我不知道如何从 FTP 服务器下载。

如何从 FTP 服务器下载最新的文件?

这是我从我的电脑下载最新文件的程序

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;
}

好的,通过这段代码我知道最后一个文件的日期,但是我怎么知道这个文件的名称????????

【问题讨论】:

    标签: c# .net ftp ftp-client


    【解决方案1】:

    您必须检索远程文件的时间戳才能选择最新的。

    不幸的是,没有真正可靠和有效的方法来使用 .NET 框架提供的功能来检索目录中所有文件的修改时间戳,因为它不支持 FTP MLSD 命令。 MLSD 命令以标准化的机器可读格式提供远程目录列表。命令和格式由RFC 3659标准化。

    .NET 框架支持的您可以使用的替代方案:


    或者,您可以使用支持现代 MLSD 命令的第 3 方 FTP 客户端实现。

    例如WinSCP .NET assembly 支持。

    甚至还有一个针对您的特定任务的示例:Downloading the most recent file
    该示例适用于 PowerShell 和 SFTP,但可以轻松转换为 C# 和 FTP:

    // 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);
    }
    

    (我是 WinSCP 的作者)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      相关资源
      最近更新 更多