C# - 下载最后修改日期较晚的FTP文件

5

我有一个FTP服务器,里面有一些文件。我在本地目录(C:\)中也有相同的文件。

当我运行程序时,希望它能搜索FTP服务器中所有最后修改时间晚于本地目录中相同文件的文件,并下载所有找到的文件。

请问有人可以给我帮助或提示吗?我将非常感激所有答案!


FTP有一个DIR选项,用于获取文件列表。请参阅网页:https://msdn.microsoft.com/en-us/library/ms229716(v=vs.110).aspx - jdweng
2个回答

5

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

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

  • the 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 ls *nix command is the most common, 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).

    Examples:
    DOS/Windows format: C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response
    *nix format: Parsing FtpWebRequest ListDirectoryDetails line

  • the GetDateTimestamp method (an FTP MDTM command) to individually retrieve timestamps for each file. An advantage is that the response is standardized by the 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);
    

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

例如,WinSCP .NET程序集 就支持该命令。

您可以使用 Session.ListDirectorySession.EnumerateRemoteFiles 方法,并读取返回的集合中文件的 RemoteFileInfo.LastWriteTime

甚至更简单的是,您可以使用 Session.SynchronizeDirectories 让库自动下载(同步)修改后的文件:

// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "user",
    Password = "mypassword",
};

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Synchronize files
    var localPath = @"d:\www";
    var remotePath = "/home/martin/public_html";
    session.SynchronizeDirectories(
        SynchronizationMode.Local, localPath, remotePath, false).Check();
}

WinSCP GUI可以为您生成代码模板

(我是WinSCP的作者)



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接